home *** CD-ROM | disk | FTP | other *** search
/ Revista do CD-ROM 151 / cd-rom 151.iso / internet / firefox / Firefox Setup 3.0 Beta 1.exe / nonlocalized / components / nsSearchService.js < prev    next >
Encoding:
Text File  |  2007-11-09  |  107.0 KB  |  3,169 lines

  1. //@line 40 "e:\builds\tinderbox\Fx-Rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  2.  
  3. const Ci = Components.interfaces;
  4. const Cc = Components.classes;
  5. const Cr = Components.results;
  6.  
  7. const PERMS_FILE      = 0644;
  8. const PERMS_DIRECTORY = 0755;
  9.  
  10. const MODE_RDONLY   = 0x01;
  11. const MODE_WRONLY   = 0x02;
  12. const MODE_CREATE   = 0x08;
  13. const MODE_APPEND   = 0x10;
  14. const MODE_TRUNCATE = 0x20;
  15.  
  16. // Directory service keys
  17. const NS_APP_SEARCH_DIR_LIST  = "SrchPluginsDL";
  18. const NS_APP_USER_SEARCH_DIR  = "UsrSrchPlugns";
  19. const NS_APP_SEARCH_DIR       = "SrchPlugns";
  20. const NS_APP_USER_PROFILE_50_DIR = "ProfD";
  21.  
  22. // Search engine "locations". If this list is changed, be sure to update
  23. // the engine's _isDefault function accordingly.
  24. const SEARCH_APP_DIR = 1;
  25. const SEARCH_PROFILE_DIR = 2;
  26. const SEARCH_IN_EXTENSION = 3;
  27.  
  28. // See documentation in nsIBrowserSearchService.idl.
  29. const SEARCH_ENGINE_TOPIC        = "browser-search-engine-modified";
  30. const QUIT_APPLICATION_TOPIC     = "quit-application";
  31.  
  32. const SEARCH_ENGINE_REMOVED      = "engine-removed";
  33. const SEARCH_ENGINE_ADDED        = "engine-added";
  34. const SEARCH_ENGINE_CHANGED      = "engine-changed";
  35. const SEARCH_ENGINE_LOADED       = "engine-loaded";
  36. const SEARCH_ENGINE_CURRENT      = "engine-current";
  37.  
  38. const SEARCH_TYPE_MOZSEARCH      = Ci.nsISearchEngine.TYPE_MOZSEARCH;
  39. const SEARCH_TYPE_OPENSEARCH     = Ci.nsISearchEngine.TYPE_OPENSEARCH;
  40. const SEARCH_TYPE_SHERLOCK       = Ci.nsISearchEngine.TYPE_SHERLOCK;
  41.  
  42. const SEARCH_DATA_XML            = Ci.nsISearchEngine.DATA_XML;
  43. const SEARCH_DATA_TEXT           = Ci.nsISearchEngine.DATA_TEXT;
  44.  
  45. // File extensions for search plugin description files
  46. const XML_FILE_EXT      = "xml";
  47. const SHERLOCK_FILE_EXT = "src";
  48.  
  49. // Delay for lazy serialization (ms)
  50. const LAZY_SERIALIZE_DELAY = 100;
  51.  
  52. const ICON_DATAURL_PREFIX = "data:image/x-icon;base64,";
  53.  
  54. // Supported extensions for Sherlock plugin icons
  55. const SHERLOCK_ICON_EXTENSIONS = [".gif", ".png", ".jpg", ".jpeg"];
  56.  
  57. const NEW_LINES = /(\r\n|\r|\n)/;
  58.  
  59. // Set an arbitrary cap on the maximum icon size. Without this, large icons can
  60. // cause big delays when loading them at startup.
  61. const MAX_ICON_SIZE   = 10000;
  62.  
  63. // Default charset to use for sending search parameters. ISO-8859-1 is used to
  64. // match previous nsInternetSearchService behavior.
  65. const DEFAULT_QUERY_CHARSET = "ISO-8859-1";
  66.  
  67. const SEARCH_BUNDLE = "chrome://browser/locale/search.properties";
  68. const BRAND_BUNDLE = "chrome://branding/locale/brand.properties";
  69.  
  70. const OPENSEARCH_NS_10  = "http://a9.com/-/spec/opensearch/1.0/";
  71. const OPENSEARCH_NS_11  = "http://a9.com/-/spec/opensearch/1.1/";
  72.  
  73. // Although the specification at http://opensearch.a9.com/spec/1.1/description/
  74. // gives the namespace names defined above, many existing OpenSearch engines
  75. // are using the following versions.  We therefore allow either.
  76. const OPENSEARCH_NAMESPACES = [
  77.   OPENSEARCH_NS_11, OPENSEARCH_NS_10,
  78.   "http://a9.com/-/spec/opensearchdescription/1.1/",
  79.   "http://a9.com/-/spec/opensearchdescription/1.0/"
  80. ];
  81.  
  82. const OPENSEARCH_LOCALNAME = "OpenSearchDescription";
  83.  
  84. const MOZSEARCH_NS_10     = "http://www.mozilla.org/2006/browser/search/";
  85. const MOZSEARCH_LOCALNAME = "SearchPlugin";
  86.  
  87. const URLTYPE_SUGGEST_JSON = "application/x-suggestions+json";
  88. const URLTYPE_SEARCH_HTML  = "text/html";
  89.  
  90. // Empty base document used to serialize engines to file.
  91. const EMPTY_DOC = "<?xml version=\"1.0\"?>\n" +
  92.                   "<" + MOZSEARCH_LOCALNAME +
  93.                   " xmlns=\"" + MOZSEARCH_NS_10 + "\"" +
  94.                   " xmlns:os=\"" + OPENSEARCH_NS_11 + "\"" +
  95.                   "/>";
  96.  
  97. const BROWSER_SEARCH_PREF = "browser.search.";
  98.  
  99. const USER_DEFINED = "{searchTerms}";
  100.  
  101. // Custom search parameters
  102. //@line 141 "e:\builds\tinderbox\Fx-Rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  103. const MOZ_OFFICIAL = "official";
  104. //@line 145 "e:\builds\tinderbox\Fx-Rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  105. const MOZ_DISTRIBUTION_ID = "org.mozilla";
  106.  
  107. const MOZ_PARAM_LOCALE         = /\{moz:locale\}/g;
  108. const MOZ_PARAM_DIST_ID        = /\{moz:distributionID\}/g;
  109. const MOZ_PARAM_OFFICIAL       = /\{moz:official\}/g;
  110.  
  111. // Supported OpenSearch parameters
  112. // See http://opensearch.a9.com/spec/1.1/querysyntax/#core
  113. const OS_PARAM_USER_DEFINED    = /\{searchTerms\??\}/g;
  114. const OS_PARAM_INPUT_ENCODING  = /\{inputEncoding\??\}/g;
  115. const OS_PARAM_LANGUAGE        = /\{language\??\}/g;
  116. const OS_PARAM_OUTPUT_ENCODING = /\{outputEncoding\??\}/g;
  117.  
  118. // Default values
  119. const OS_PARAM_LANGUAGE_DEF         = "*";
  120. const OS_PARAM_OUTPUT_ENCODING_DEF  = "UTF-8";
  121. const OS_PARAM_INPUT_ENCODING_DEF   = "UTF-8";
  122.  
  123. // "Unsupported" OpenSearch parameters. For example, we don't support
  124. // page-based results, so if the engine requires that we send the "page index"
  125. // parameter, we'll always send "1".
  126. const OS_PARAM_COUNT        = /\{count\??\}/g;
  127. const OS_PARAM_START_INDEX  = /\{startIndex\??\}/g;
  128. const OS_PARAM_START_PAGE   = /\{startPage\??\}/g;
  129.  
  130. // Default values
  131. const OS_PARAM_COUNT_DEF        = "20"; // 20 results
  132. const OS_PARAM_START_INDEX_DEF  = "1";  // start at 1st result
  133. const OS_PARAM_START_PAGE_DEF   = "1";  // 1st page
  134.  
  135. // Optional parameter
  136. const OS_PARAM_OPTIONAL     = /\{(?:\w+:)?\w+\?\}/g;
  137.  
  138. // A array of arrays containing parameters that we don't fully support, and
  139. // their default values. We will only send values for these parameters if
  140. // required, since our values are just really arbitrary "guesses" that should
  141. // give us the output we want.
  142. var OS_UNSUPPORTED_PARAMS = [
  143.   [OS_PARAM_COUNT, OS_PARAM_COUNT_DEF],
  144.   [OS_PARAM_START_INDEX, OS_PARAM_START_INDEX_DEF],
  145.   [OS_PARAM_START_PAGE, OS_PARAM_START_PAGE_DEF],
  146. ];
  147.  
  148. // The default engine update interval, in days. This is only used if an engine
  149. // specifies an updateURL, but not an updateInterval.
  150. const SEARCH_DEFAULT_UPDATE_INTERVAL = 7;
  151.  
  152. // Returns false for whitespace-only or commented out lines in a
  153. // Sherlock file, true otherwise.
  154. function isUsefulLine(aLine) {
  155.   return !(/^\s*($|#)/i.test(aLine));
  156. }
  157.  
  158. /**
  159.  * Prefixed to all search debug output.
  160.  */
  161. const SEARCH_LOG_PREFIX = "*** Search: ";
  162.  
  163. /**
  164.  * Outputs aText to the JavaScript console as well as to stdout, if the search
  165.  * logging pref (browser.search.log) is set to true.
  166.  */
  167. function LOG(aText) {
  168. //@line 223 "e:\builds\tinderbox\Fx-Rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  169. }
  170.  
  171. function ERROR(message, resultCode) {
  172.   NS_ASSERT(false, SEARCH_LOG_PREFIX + message);
  173.   throw resultCode;
  174. }
  175.  
  176. /**
  177.  * Ensures an assertion is met before continuing. Should be used to indicate
  178.  * fatal errors.
  179.  * @param  assertion
  180.  *         An assertion that must be met
  181.  * @param  message
  182.  *         A message to display if the assertion is not met
  183.  * @param  resultCode
  184.  *         The NS_ERROR_* value to throw if the assertion is not met
  185.  * @throws resultCode
  186.  */
  187. function ENSURE_WARN(assertion, message, resultCode) {
  188.   NS_ASSERT(assertion, SEARCH_LOG_PREFIX + message);
  189.   if (!assertion)
  190.     throw resultCode;
  191. }
  192.  
  193. /**
  194.  * Ensures an assertion is met before continuing, but does not warn the user.
  195.  * Used to handle normal failure conditions.
  196.  * @param  assertion
  197.  *         An assertion that must be met
  198.  * @param  message
  199.  *         A message to display if the assertion is not met
  200.  * @param  resultCode
  201.  *         The NS_ERROR_* value to throw if the assertion is not met
  202.  * @throws resultCode
  203.  */
  204. function ENSURE(assertion, message, resultCode) {
  205.   if (!assertion) {
  206.     LOG(message);
  207.     throw resultCode;
  208.   }
  209. }
  210.  
  211. /**
  212.  * Ensures an argument assertion is met before continuing.
  213.  * @param  assertion
  214.  *         An argument assertion that must be met
  215.  * @param  message
  216.  *         A message to display if the assertion is not met
  217.  * @throws NS_ERROR_INVALID_ARG for invalid arguments
  218.  */
  219. function ENSURE_ARG(assertion, message) {
  220.   ENSURE(assertion, message, Cr.NS_ERROR_INVALID_ARG);
  221. }
  222.  
  223. function loadListener(aChannel, aEngine, aCallback) {
  224.   this._channel = aChannel;
  225.   this._bytes = [];
  226.   this._engine = aEngine;
  227.   this._callback = aCallback;
  228. }
  229. loadListener.prototype = {
  230.   _callback: null,
  231.   _channel: null,
  232.   _countRead: 0,
  233.   _engine: null,
  234.   _stream: null,
  235.  
  236.   QueryInterface: function SRCH_loadQI(aIID) {
  237.     if (aIID.equals(Ci.nsISupports)           ||
  238.         aIID.equals(Ci.nsIRequestObserver)    ||
  239.         aIID.equals(Ci.nsIStreamListener)     ||
  240.         aIID.equals(Ci.nsIChannelEventSink)   ||
  241.         aIID.equals(Ci.nsIInterfaceRequestor) ||
  242.         // See FIXME comment below
  243.         aIID.equals(Ci.nsIHttpEventSink)      ||
  244.         aIID.equals(Ci.nsIProgressEventSink)  ||
  245.         false)
  246.       return this;
  247.  
  248.     throw Cr.NS_ERROR_NO_INTERFACE;
  249.   },
  250.  
  251.   // nsIRequestObserver
  252.   onStartRequest: function SRCH_loadStartR(aRequest, aContext) {
  253.     LOG("loadListener: Starting request: " + aRequest.name);
  254.     this._stream = Cc["@mozilla.org/binaryinputstream;1"].
  255.                    createInstance(Ci.nsIBinaryInputStream);
  256.   },
  257.  
  258.   onStopRequest: function SRCH_loadStopR(aRequest, aContext, aStatusCode) {
  259.     LOG("loadListener: Stopping request: " + aRequest.name);
  260.  
  261.     var requestFailed = !Components.isSuccessCode(aStatusCode);
  262.     if (!requestFailed && (aRequest instanceof Ci.nsIHttpChannel))
  263.       requestFailed = !aRequest.requestSucceeded;
  264.  
  265.     if (requestFailed || this._countRead == 0) {
  266.       LOG("loadListener: request failed!");
  267.       // send null so the callback can deal with the failure
  268.       this._callback(null, this._engine);
  269.     } else
  270.       this._callback(this._bytes, this._engine);
  271.     this._channel = null;
  272.     this._engine  = null;
  273.   },
  274.  
  275.   // nsIStreamListener
  276.   onDataAvailable: function SRCH_loadDAvailable(aRequest, aContext,
  277.                                                 aInputStream, aOffset,
  278.                                                 aCount) {
  279.     this._stream.setInputStream(aInputStream);
  280.  
  281.     // Get a byte array of the data
  282.     this._bytes = this._bytes.concat(this._stream.readByteArray(aCount));
  283.     this._countRead += aCount;
  284.   },
  285.  
  286.   // nsIChannelEventSink
  287.   onChannelRedirect: function SRCH_loadCRedirect(aOldChannel, aNewChannel,
  288.                                                  aFlags) {
  289.     this._channel = aNewChannel;
  290.   },
  291.  
  292.   // nsIInterfaceRequestor
  293.   getInterface: function SRCH_load_GI(aIID) {
  294.     return this.QueryInterface(aIID);
  295.   },
  296.  
  297.   // FIXME: bug 253127
  298.   // nsIHttpEventSink
  299.   onRedirect: function (aChannel, aNewChannel) {},
  300.   // nsIProgressEventSink
  301.   onProgress: function (aRequest, aContext, aProgress, aProgressMax) {},
  302.   onStatus: function (aRequest, aContext, aStatus, aStatusArg) {}
  303. }
  304.  
  305.  
  306. /**
  307.  * Used to verify a given DOM node's localName and namespaceURI.
  308.  * @param aElement
  309.  *        The element to verify.
  310.  * @param aLocalNameArray
  311.  *        An array of strings to compare against aElement's localName.
  312.  * @param aNameSpaceArray
  313.  *        An array of strings to compare against aElement's namespaceURI.
  314.  *
  315.  * @returns false if aElement is null, or if its localName or namespaceURI
  316.  *          does not match one of the elements in the aLocalNameArray or
  317.  *          aNameSpaceArray arrays, respectively.
  318.  * @throws NS_ERROR_INVALID_ARG if aLocalNameArray or aNameSpaceArray are null.
  319.  */
  320. function checkNameSpace(aElement, aLocalNameArray, aNameSpaceArray) {
  321.   ENSURE_ARG(aLocalNameArray && aNameSpaceArray, "missing aLocalNameArray or \
  322.              aNameSpaceArray for checkNameSpace");
  323.   return (aElement                                                &&
  324.           (aLocalNameArray.indexOf(aElement.localName)    != -1)  &&
  325.           (aNameSpaceArray.indexOf(aElement.namespaceURI) != -1));
  326. }
  327.  
  328. /**
  329.  * Safely close a nsISafeOutputStream.
  330.  * @param aFOS
  331.  *        The file output stream to close.
  332.  */
  333. function closeSafeOutputStream(aFOS) {
  334.   if (aFOS instanceof Ci.nsISafeOutputStream) {
  335.     try {
  336.       aFOS.finish();
  337.       return;
  338.     } catch (e) { }
  339.   }
  340.   aFOS.close();
  341. }
  342.  
  343. /**
  344.  * Wrapper function for nsIIOService::newURI.
  345.  * @param aURLSpec
  346.  *        The URL string from which to create an nsIURI.
  347.  * @returns an nsIURI object, or null if the creation of the URI failed.
  348.  */
  349. function makeURI(aURLSpec, aCharset) {
  350.   var ios = Cc["@mozilla.org/network/io-service;1"].
  351.             getService(Ci.nsIIOService);
  352.   try {
  353.     return ios.newURI(aURLSpec, aCharset, null);
  354.   } catch (ex) { }
  355.  
  356.   return null;
  357. }
  358.  
  359. /**
  360.  * Gets a directory from the directory service.
  361.  * @param aKey
  362.  *        The directory service key indicating the directory to get.
  363.  */
  364. function getDir(aKey) {
  365.   ENSURE_ARG(aKey, "getDir requires a directory key!");
  366.  
  367.   var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
  368.                     getService(Ci.nsIProperties);
  369.   var dir = fileLocator.get(aKey, Ci.nsIFile);
  370.   return dir;
  371. }
  372.  
  373. /**
  374.  * The following two functions are essentially copied from
  375.  * nsInternetSearchService. They are required for backwards compatibility.
  376.  */
  377. function queryCharsetFromCode(aCode) {
  378.   const codes = [];
  379.   codes[0] = "x-mac-roman";
  380.   codes[6] = "x-mac-greek";
  381.   codes[35] = "x-mac-turkish";
  382.   codes[513] = "ISO-8859-1";
  383.   codes[514] = "ISO-8859-2";
  384.   codes[517] = "ISO-8859-5";
  385.   codes[518] = "ISO-8859-6";
  386.   codes[519] = "ISO-8859-7";
  387.   codes[520] = "ISO-8859-8";
  388.   codes[521] = "ISO-8859-9";
  389.   codes[1049] = "IBM864";
  390.   codes[1280] = "windows-1252";
  391.   codes[1281] = "windows-1250";
  392.   codes[1282] = "windows-1251";
  393.   codes[1283] = "windows-1253";
  394.   codes[1284] = "windows-1254";
  395.   codes[1285] = "windows-1255";
  396.   codes[1286] = "windows-1256";
  397.   codes[1536] = "us-ascii";
  398.   codes[1584] = "GB2312";
  399.   codes[1585] = "x-gbk";
  400.   codes[1600] = "EUC-KR";
  401.   codes[2080] = "ISO-2022-JP";
  402.   codes[2096] = "ISO-2022-CN";
  403.   codes[2112] = "ISO-2022-KR";
  404.   codes[2336] = "EUC-JP";
  405.   codes[2352] = "GB2312";
  406.   codes[2353] = "x-euc-tw";
  407.   codes[2368] = "EUC-KR";
  408.   codes[2561] = "Shift_JIS";
  409.   codes[2562] = "KOI8-R";
  410.   codes[2563] = "Big5";
  411.   codes[2565] = "HZ-GB-2312";
  412.  
  413.   if (codes[aCode])
  414.     return codes[aCode];
  415.  
  416.   return getLocalizedPref("intl.charset.default", DEFAULT_QUERY_CHARSET);
  417. }
  418. function fileCharsetFromCode(aCode) {
  419.   const codes = [
  420.     "x-mac-roman",           // 0
  421.     "Shift_JIS",             // 1
  422.     "Big5",                  // 2
  423.     "EUC-KR",                // 3
  424.     "X-MAC-ARABIC",          // 4
  425.     "X-MAC-HEBREW",          // 5
  426.     "X-MAC-GREEK",           // 6
  427.     "X-MAC-CYRILLIC",        // 7
  428.     "X-MAC-DEVANAGARI" ,     // 9
  429.     "X-MAC-GURMUKHI",        // 10
  430.     "X-MAC-GUJARATI",        // 11
  431.     "X-MAC-ORIYA",           // 12
  432.     "X-MAC-BENGALI",         // 13
  433.     "X-MAC-TAMIL",           // 14
  434.     "X-MAC-TELUGU",          // 15
  435.     "X-MAC-KANNADA",         // 16
  436.     "X-MAC-MALAYALAM",       // 17
  437.     "X-MAC-SINHALESE",       // 18
  438.     "X-MAC-BURMESE",         // 19
  439.     "X-MAC-KHMER",           // 20
  440.     "X-MAC-THAI",            // 21
  441.     "X-MAC-LAOTIAN",         // 22
  442.     "X-MAC-GEORGIAN",        // 23
  443.     "X-MAC-ARMENIAN",        // 24
  444.     "GB2312",                // 25
  445.     "X-MAC-TIBETAN",         // 26
  446.     "X-MAC-MONGOLIAN",       // 27
  447.     "X-MAC-ETHIOPIC",        // 28
  448.     "X-MAC-CENTRALEURROMAN", // 29
  449.     "X-MAC-VIETNAMESE",      // 30
  450.     "X-MAC-EXTARABIC"        // 31
  451.   ];
  452.   // Sherlock files have always defaulted to x-mac-roman, so do that here too
  453.   return codes[aCode] || codes[0];
  454. }
  455.  
  456. /**
  457.  * Returns a string interpretation of aBytes using aCharset, or null on
  458.  * failure.
  459.  */
  460. function bytesToString(aBytes, aCharset) {
  461.   var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
  462.                   createInstance(Ci.nsIScriptableUnicodeConverter);
  463.   LOG("bytesToString: converting using charset: " + aCharset);
  464.  
  465.   try {
  466.     converter.charset = aCharset;
  467.     return converter.convertFromByteArray(aBytes, aBytes.length);
  468.   } catch (ex) {}
  469.  
  470.   return null;
  471. }
  472.  
  473. /**
  474.  * Converts an array of bytes representing a Sherlock file into an array of
  475.  * lines representing the useful data from the file.
  476.  *
  477.  * @param aBytes
  478.  *        The array of bytes representing the Sherlock file.
  479.  * @param aCharsetCode
  480.  *        An integer value representing a character set code to be passed to
  481.  *        fileCharsetFromCode, or null for the default Sherlock encoding.
  482.  */
  483. function sherlockBytesToLines(aBytes, aCharsetCode) {
  484.   // fileCharsetFromCode returns the default encoding if aCharsetCode is null
  485.   var charset = fileCharsetFromCode(aCharsetCode);
  486.  
  487.   var dataString = bytesToString(aBytes, charset);
  488.   ENSURE(dataString, "sherlockBytesToLines: Couldn't convert byte array!",
  489.          Cr.NS_ERROR_FAILURE);
  490.  
  491.   // Split the string into lines, and filter out comments and
  492.   // whitespace-only lines
  493.   return dataString.split(NEW_LINES).filter(isUsefulLine);
  494. }
  495.  
  496. /**
  497.  * Gets the current value of the locale.  It's possible for this preference to
  498.  * be localized, so we have to do a little extra work here.  Similar code
  499.  * exists in nsHttpHandler.cpp when building the UA string.
  500.  */
  501. function getLocale() {
  502.   const localePref = "general.useragent.locale";
  503.   var locale = getLocalizedPref(localePref);
  504.   if (locale)
  505.     return locale;
  506.  
  507.   // Not localized
  508.   var prefs = Cc["@mozilla.org/preferences-service;1"].
  509.               getService(Ci.nsIPrefBranch);
  510.   return prefs.getCharPref(localePref);
  511. }
  512.  
  513. /**
  514.  * Wrapper for nsIPrefBranch::getComplexValue.
  515.  * @param aPrefName
  516.  *        The name of the pref to get.
  517.  * @returns aDefault if the requested pref doesn't exist.
  518.  */
  519. function getLocalizedPref(aPrefName, aDefault) {
  520.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  521.               getService(Ci.nsIPrefBranch);
  522.   const nsIPLS = Ci.nsIPrefLocalizedString;
  523.   try {
  524.     return prefB.getComplexValue(aPrefName, nsIPLS).data;
  525.   } catch (ex) {}
  526.  
  527.   return aDefault;
  528. }
  529.  
  530. /**
  531.  * Wrapper for nsIPrefBranch::setComplexValue.
  532.  * @param aPrefName
  533.  *        The name of the pref to set.
  534.  */
  535. function setLocalizedPref(aPrefName, aValue) {
  536.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  537.               getService(Ci.nsIPrefBranch);
  538.   const nsIPLS = Ci.nsIPrefLocalizedString;
  539.   try {
  540.     var pls = Components.classes["@mozilla.org/pref-localizedstring;1"]
  541.                         .createInstance(Ci.nsIPrefLocalizedString);
  542.     pls.data = aValue;
  543.     prefB.setComplexValue(aPrefName, nsIPLS, pls);
  544.   } catch (ex) {}
  545. }
  546.  
  547. /**
  548.  * Wrapper for nsIPrefBranch::getBoolPref.
  549.  * @param aPrefName
  550.  *        The name of the pref to get.
  551.  * @returns aDefault if the requested pref doesn't exist.
  552.  */
  553. function getBoolPref(aName, aDefault) {
  554.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  555.               getService(Ci.nsIPrefBranch);
  556.   try {
  557.     return prefB.getBoolPref(aName);
  558.   } catch (ex) {
  559.     return aDefault;
  560.   }
  561. }
  562.  
  563. /**
  564.  * Get a unique nsIFile object with a sanitized name, based on the engine name.
  565.  * @param aName
  566.  *        A name to "sanitize". Can be an empty string, in which case a random
  567.  *        8 character filename will be produced.
  568.  * @returns A nsIFile object in the user's search engines directory with a
  569.  *          unique sanitized name.
  570.  */
  571. function getSanitizedFile(aName) {
  572.   var fileName = sanitizeName(aName) + "." + XML_FILE_EXT;
  573.   var file = getDir(NS_APP_USER_SEARCH_DIR);
  574.   file.append(fileName);
  575.   file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, PERMS_FILE);
  576.   return file;
  577. }
  578.  
  579. /**
  580.  * Removes all characters not in the "chars" string from aName.
  581.  *
  582.  * @returns a sanitized name to be used as a filename, or a random name
  583.  *          if a sanitized name cannot be obtained (if aName contains
  584.  *          no valid characters).
  585.  */
  586. function sanitizeName(aName) {
  587.   const chars = "-abcdefghijklmnopqrstuvwxyz0123456789";
  588.   const maxLength = 60;
  589.  
  590.   var name = aName.toLowerCase();
  591.   name = name.replace(/ /g, "-");
  592.   name = name.split("").filter(function (el) {
  593.                                  return chars.indexOf(el) != -1;
  594.                                }).join("");
  595.  
  596.   if (!name) {
  597.     // Our input had no valid characters - use a random name
  598.     var cl = chars.length - 1;
  599.     for (var i = 0; i < 8; ++i)
  600.       name += chars.charAt(Math.round(Math.random() * cl));
  601.   }
  602.  
  603.   if (name.length > maxLength)
  604.     name = name.substring(0, maxLength);
  605.  
  606.   return name;
  607. }
  608.  
  609. /**
  610.  * Notifies watchers of SEARCH_ENGINE_TOPIC about changes to an engine or to
  611.  * the state of the search service.
  612.  *
  613.  * @param aEngine
  614.  *        The nsISearchEngine object to which the change applies.
  615.  * @param aVerb
  616.  *        A verb describing the change.
  617.  *
  618.  * @see nsIBrowserSearchService.idl
  619.  */
  620. function notifyAction(aEngine, aVerb) {
  621.   var os = Cc["@mozilla.org/observer-service;1"].
  622.            getService(Ci.nsIObserverService);
  623.   LOG("NOTIFY: Engine: \"" + aEngine.name + "\"; Verb: \"" + aVerb + "\"");
  624.   os.notifyObservers(aEngine, SEARCH_ENGINE_TOPIC, aVerb);
  625. }
  626.  
  627. /**
  628.  * Simple object representing a name/value pair.
  629.  */
  630. function QueryParameter(aName, aValue) {
  631.   ENSURE_ARG(aName && (aValue != null),
  632.              "missing name or value for QueryParameter!");
  633.  
  634.   this.name = aName;
  635.   this.value = aValue;
  636. }
  637.  
  638. /**
  639.  * Perform OpenSearch parameter substitution on aParamValue.
  640.  *
  641.  * @param aParamValue
  642.  *        A string containing OpenSearch search parameters.
  643.  * @param aSearchTerms
  644.  *        The user-provided search terms. This string will inserted into
  645.  *        aParamValue as the value of the OS_PARAM_USER_DEFINED parameter.
  646.  *        This value must already be escaped appropriately - it is inserted
  647.  *        as-is.
  648.  * @param aQueryEncoding
  649.  *        The value to use for the OS_PARAM_INPUT_ENCODING parameter. See
  650.  *        definition in the OpenSearch spec.
  651.  *
  652.  * @see http://opensearch.a9.com/spec/1.1/querysyntax/#core
  653.  */
  654. function ParamSubstitution(aParamValue, aSearchTerms, aEngine) {
  655.   var value = aParamValue;
  656.  
  657.   var distributionID = MOZ_DISTRIBUTION_ID;
  658.   try {
  659.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  660.                 getService(Ci.nsIPrefBranch);
  661.     distributionID = prefB.getCharPref(BROWSER_SEARCH_PREF + "distributionID");
  662.   }
  663.   catch (ex) { }
  664.  
  665.   // Custom search parameters. These are only available to default search
  666.   // engines.
  667.   if (aEngine._isDefault) {
  668.     value = value.replace(MOZ_PARAM_LOCALE, getLocale());
  669.     value = value.replace(MOZ_PARAM_DIST_ID, distributionID);
  670.     value = value.replace(MOZ_PARAM_OFFICIAL, MOZ_OFFICIAL);
  671.   }
  672.  
  673.   // Insert the OpenSearch parameters we're confident about
  674.   value = value.replace(OS_PARAM_USER_DEFINED, aSearchTerms);
  675.   value = value.replace(OS_PARAM_INPUT_ENCODING, aEngine.queryCharset);
  676.   value = value.replace(OS_PARAM_LANGUAGE,
  677.                         getLocale() || OS_PARAM_LANGUAGE_DEF);
  678.   value = value.replace(OS_PARAM_OUTPUT_ENCODING,
  679.                         OS_PARAM_OUTPUT_ENCODING_DEF);
  680.  
  681.   // Replace any optional parameters
  682.   value = value.replace(OS_PARAM_OPTIONAL, "");
  683.  
  684.   // Insert any remaining required params with our default values
  685.   for (var i = 0; i < OS_UNSUPPORTED_PARAMS.length; ++i) {
  686.     value = value.replace(OS_UNSUPPORTED_PARAMS[i][0],
  687.                           OS_UNSUPPORTED_PARAMS[i][1]);
  688.   }
  689.  
  690.   return value;
  691. }
  692.  
  693. /**
  694.  * Creates a mozStorage statement that can be used to access the database we
  695.  * use to hold metadata.
  696.  *
  697.  * @param dbconn  the database that the statement applies to
  698.  * @param sql     a string specifying the sql statement that should be created
  699.  */
  700. function createStatement (dbconn, sql) {
  701.   var stmt = dbconn.createStatement(sql);
  702.   var wrapper = Cc["@mozilla.org/storage/statement-wrapper;1"].
  703.                 createInstance(Ci.mozIStorageStatementWrapper);
  704.  
  705.   wrapper.initialize(stmt);
  706.   return wrapper;
  707. }
  708.  
  709. /**
  710.  * Creates an engineURL object, which holds the query URL and all parameters.
  711.  *
  712.  * @param aType
  713.  *        A string containing the name of the MIME type of the search results
  714.  *        returned by this URL.
  715.  * @param aMethod
  716.  *        The HTTP request method. Must be a case insensitive value of either
  717.  *        "GET" or "POST".
  718.  * @param aTemplate
  719.  *        The URL to which search queries should be sent. For GET requests,
  720.  *        must contain the string "{searchTerms}", to indicate where the user
  721.  *        entered search terms should be inserted.
  722.  *
  723.  * @see http://opensearch.a9.com/spec/1.1/querysyntax/#urltag
  724.  *
  725.  * @throws NS_ERROR_NOT_IMPLEMENTED if aType is unsupported.
  726.  */
  727. function EngineURL(aType, aMethod, aTemplate) {
  728.   ENSURE_ARG(aType && aMethod && aTemplate,
  729.              "missing type, method or template for EngineURL!");
  730.  
  731.   var method = aMethod.toUpperCase();
  732.   var type   = aType.toLowerCase();
  733.  
  734.   ENSURE_ARG(method == "GET" || method == "POST",
  735.              "method passed to EngineURL must be \"GET\" or \"POST\"");
  736.  
  737.   this.type     = type;
  738.   this.method   = method;
  739.   this.params   = [];
  740.  
  741.   var templateURI = makeURI(aTemplate);
  742.   ENSURE(templateURI, "new EngineURL: template is not a valid URI!",
  743.          Cr.NS_ERROR_FAILURE);
  744.  
  745.   switch (templateURI.scheme) {
  746.     case "http":
  747.     case "https":
  748.     // Disable these for now, see bug 295018
  749.     // case "file":
  750.     // case "resource":
  751.       this.template = aTemplate;
  752.       break;
  753.     default:
  754.       ENSURE(false, "new EngineURL: template uses invalid scheme!",
  755.              Cr.NS_ERROR_FAILURE);
  756.   }
  757. }
  758. EngineURL.prototype = {
  759.  
  760.   addParam: function SRCH_EURL_addParam(aName, aValue) {
  761.     this.params.push(new QueryParameter(aName, aValue));
  762.   },
  763.  
  764.   getSubmission: function SRCH_EURL_getSubmission(aSearchTerms, aEngine) {
  765.     var url = ParamSubstitution(this.template, aSearchTerms, aEngine);
  766.  
  767.     // Create an application/x-www-form-urlencoded representation of our params
  768.     // (name=value&name=value&name=value)
  769.     var dataString = "";
  770.     for (var i = 0; i < this.params.length; ++i) {
  771.       var param = this.params[i];
  772.       var value = ParamSubstitution(param.value, aSearchTerms, aEngine);
  773.  
  774.       dataString += (i > 0 ? "&" : "") + param.name + "=" + value;
  775.     }
  776.  
  777.     var postData = null;
  778.     if (this.method == "GET") {
  779.       // GET method requests have no post data, and append the encoded
  780.       // query string to the url...
  781.       if (url.indexOf("?") == -1 && dataString)
  782.         url += "?";
  783.       url += dataString;
  784.     } else if (this.method == "POST") {
  785.       // POST method requests must wrap the encoded text in a MIME
  786.       // stream and supply that as POSTDATA.
  787.       var stringStream = Cc["@mozilla.org/io/string-input-stream;1"].
  788.                          createInstance(Ci.nsIStringInputStream);
  789. //@line 847 "e:\builds\tinderbox\Fx-Rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  790.       stringStream.data = dataString;
  791. //@line 849 "e:\builds\tinderbox\Fx-Rel\WINNT_5.2_Depend\mozilla\browser\components\search\nsSearchService.js"
  792.  
  793.       postData = Cc["@mozilla.org/network/mime-input-stream;1"].
  794.                  createInstance(Ci.nsIMIMEInputStream);
  795.       postData.addHeader("Content-Type", "application/x-www-form-urlencoded");
  796.       postData.addContentLength = true;
  797.       postData.setData(stringStream);
  798.     }
  799.  
  800.     return new Submission(makeURI(url), postData);
  801.   },
  802.  
  803.   /**
  804.    * Serializes the engine object to a OpenSearch Url element.
  805.    * @param aDoc
  806.    *        The document to use to create the Url element.
  807.    * @param aElement
  808.    *        The element to which the created Url element is appended.
  809.    *
  810.    * @see http://opensearch.a9.com/spec/1.1/querysyntax/#urltag
  811.    */
  812.   _serializeToElement: function SRCH_EURL_serializeToEl(aDoc, aElement) {
  813.     var url = aDoc.createElementNS(OPENSEARCH_NS_11, "Url");
  814.     url.setAttribute("type", this.type);
  815.     url.setAttribute("method", this.method);
  816.     url.setAttribute("template", this.template);
  817.  
  818.     for (var i = 0; i < this.params.length; ++i) {
  819.       var param = aDoc.createElementNS(OPENSEARCH_NS_11, "Param");
  820.       param.setAttribute("name", this.params[i].name);
  821.       param.setAttribute("value", this.params[i].value);
  822.       url.appendChild(aDoc.createTextNode("\n  "));
  823.       url.appendChild(param);
  824.     }
  825.     url.appendChild(aDoc.createTextNode("\n"));
  826.     aElement.appendChild(url);
  827.   }
  828. };
  829.  
  830. /**
  831.  * nsISearchEngine constructor.
  832.  * @param aLocation
  833.  *        A nsILocalFile or nsIURI object representing the location of the
  834.  *        search engine data file.
  835.  * @param aSourceDataType
  836.  *        The data type of the file used to describe the engine. Must be either
  837.  *        DATA_XML or DATA_TEXT.
  838.  * @param aIsReadOnly
  839.  *        Boolean indicating whether the engine should be treated as read-only.
  840.  *        Read only engines cannot be serialized to file.
  841.  */
  842. function Engine(aLocation, aSourceDataType, aIsReadOnly) {
  843.   this._dataType = aSourceDataType;
  844.   this._readOnly = aIsReadOnly;
  845.   this._urls = [];
  846.  
  847.   if (aLocation instanceof Ci.nsILocalFile) {
  848.     // we already have a file (e.g. loading engines from disk)
  849.     this._file = aLocation;
  850.   } else if (aLocation instanceof Ci.nsIURI) {
  851.     this._uri = aLocation;
  852.     switch (aLocation.scheme) {
  853.       case "https":
  854.       case "http":
  855.       case "ftp":
  856.       case "data":
  857.       case "file":
  858.       case "resource":
  859.         this._uri = aLocation;
  860.         break;
  861.       default:
  862.         ERROR("Invalid URI passed to the nsISearchEngine constructor",
  863.               Cr.NS_ERROR_INVALID_ARG);
  864.     }
  865.   } else
  866.     ERROR("Engine location is neither a File nor a URI object",
  867.           Cr.NS_ERROR_INVALID_ARG);
  868. }
  869.  
  870. Engine.prototype = {
  871.   // The engine's alias.
  872.   _alias: null,
  873.   // The data describing the engine. Is either an array of bytes, for Sherlock
  874.   // files, or an XML document element, for XML plugins.
  875.   _data: null,
  876.   // The engine's data type. See data types (DATA_) defined above.
  877.   _dataType: null,
  878.   // Whether or not the engine is readonly.
  879.   _readOnly: true,
  880.   // The engine's description
  881.   _description: "",
  882.   // Used to store the engine to replace, if we're an update to an existing
  883.   // engine.
  884.   _engineToUpdate: null,
  885.   // The file from which the plugin was loaded.
  886.   _file: null,
  887.   // Set to true if the engine has a preferred icon (an icon that should not be
  888.   // overridden by a non-preferred icon).
  889.   _hasPreferredIcon: null,
  890.   // Whether the engine is hidden from the user.
  891.   _hidden: null,
  892.   // The engine's name.
  893.   _name: null,
  894.   // The engine type. See engine types (TYPE_) defined above.
  895.   _type: null,
  896.   // The name of the charset used to submit the search terms.
  897.   _queryCharset: null,
  898.   // A URL string pointing to the engine's search form.
  899.   _searchForm: null,
  900.   // The URI object from which the engine was retrieved.
  901.   // This is null for local plugins, and is used for error messages and logging.
  902.   _uri: null,
  903.   // Whether to obtain user confirmation before adding the engine. This is only
  904.   // used when the engine is first added to the list.
  905.   _confirm: false,
  906.   // Whether to set this as the current engine as soon as it is loaded.  This
  907.   // is only used when the engine is first added to the list.
  908.   _useNow: true,
  909.   // Where the engine was loaded from. Can be one of: SEARCH_APP_DIR,
  910.   // SEARCH_PROFILE_DIR, SEARCH_IN_EXTENSION.
  911.   __installLocation: null,
  912.   // The number of days between update checks for new versions
  913.   _updateInterval: null,
  914.   // The url to check at for a new update
  915.   _updateURL: null,
  916.   // The url to check for a new icon
  917.   _iconUpdateURL: null,
  918.   // A reference to the timer used for lazily serializing the engine to file
  919.   _serializeTimer: null,
  920.  
  921.   /**
  922.    * Retrieves the data from the engine's file. If the engine's dataType is
  923.    * XML, the document element is placed in the engine's data field. For text
  924.    * engines, the data is just read directly from file and placed as an array
  925.    * of lines in the engine's data field.
  926.    */
  927.   _initFromFile: function SRCH_ENG_initFromFile() {
  928.     ENSURE(this._file && this._file.exists(),
  929.            "File must exist before calling initFromFile!",
  930.            Cr.NS_ERROR_UNEXPECTED);
  931.  
  932.     var fileInStream = Cc["@mozilla.org/network/file-input-stream;1"].
  933.                        createInstance(Ci.nsIFileInputStream);
  934.  
  935.     fileInStream.init(this._file, MODE_RDONLY, PERMS_FILE, false);
  936.  
  937.     switch (this._dataType) {
  938.       case SEARCH_DATA_XML:
  939.         var domParser = Cc["@mozilla.org/xmlextras/domparser;1"].
  940.                         createInstance(Ci.nsIDOMParser);
  941.         var doc = domParser.parseFromStream(fileInStream, "UTF-8",
  942.                                             this._file.fileSize,
  943.                                             "text/xml");
  944.  
  945.         this._data = doc.documentElement;
  946.         break;
  947.       case SEARCH_DATA_TEXT:
  948.         var binaryInStream = Cc["@mozilla.org/binaryinputstream;1"].
  949.                              createInstance(Ci.nsIBinaryInputStream);
  950.         binaryInStream.setInputStream(fileInStream);
  951.  
  952.         var bytes = binaryInStream.readByteArray(binaryInStream.available());
  953.         this._data = bytes;
  954.  
  955.         break;
  956.       default:
  957.         ERROR("Bogus engine _dataType: \"" + this._dataType + "\"",
  958.               Cr.NS_ERROR_UNEXPECTED);
  959.     }
  960.     fileInStream.close();
  961.  
  962.     // Now that the data is loaded, initialize the engine object
  963.     this._initFromData();
  964.   },
  965.  
  966.   /**
  967.    * Retrieves the engine data from a URI.
  968.    */
  969.   _initFromURI: function SRCH_ENG_initFromURI() {
  970.     ENSURE_WARN(this._uri instanceof Ci.nsIURI,
  971.                 "Must have URI when calling _initFromURI!",
  972.                 Cr.NS_ERROR_UNEXPECTED);
  973.  
  974.     LOG("_initFromURI: Downloading engine from: \"" + this._uri.spec + "\".");
  975.  
  976.     var ios = Cc["@mozilla.org/network/io-service;1"].
  977.               getService(Ci.nsIIOService);
  978.     var chan = ios.newChannelFromURI(this._uri);
  979.  
  980.     if (this._engineToUpdate && (chan instanceof Ci.nsIHttpChannel)) {
  981.       var lastModified = engineMetadataService.getAttr(this._engineToUpdate,
  982.                                                        "updatelastmodified");
  983.       if (lastModified)
  984.         chan.setRequestHeader("If-Modified-Since", lastModified, false);
  985.     }
  986.     var listener = new loadListener(chan, this, this._onLoad);
  987.     chan.notificationCallbacks = listener;
  988.     chan.asyncOpen(listener, null);
  989.   },
  990.  
  991.   /**
  992.    * Attempts to find an EngineURL object in the set of EngineURLs for
  993.    * this Engine that has the given type string.  (This corresponds to the
  994.    * "type" attribute in the "Url" node in the OpenSearch spec.)
  995.    * This method will return the first matching URL object found, or null
  996.    * if no matching URL is found.
  997.    *
  998.    * @param aType string to match the EngineURL's type attribute
  999.    */
  1000.   _getURLOfType: function SRCH_ENG__getURLOfType(aType) {
  1001.     for (var i = 0; i < this._urls.length; ++i) {
  1002.       if (this._urls[i].type == aType)
  1003.         return this._urls[i];
  1004.     }
  1005.  
  1006.     return null;
  1007.   },
  1008.  
  1009.   _confirmAddEngine: function SRCH_SVC_confirmAddEngine() {
  1010.     var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  1011.               getService(Ci.nsIStringBundleService);
  1012.     var stringBundle = sbs.createBundle(SEARCH_BUNDLE);
  1013.     var titleMessage = stringBundle.GetStringFromName("addEngineConfirmTitle");
  1014.  
  1015.     // Display only the hostname portion of the URL.
  1016.     var dialogMessage =
  1017.         stringBundle.formatStringFromName("addEngineConfirmation",
  1018.                                           [this._name, this._uri.host], 2);
  1019.     var checkboxMessage = stringBundle.GetStringFromName("addEngineUseNowText");
  1020.     var addButtonLabel =
  1021.         stringBundle.GetStringFromName("addEngineAddButtonLabel");
  1022.  
  1023.     var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  1024.              getService(Ci.nsIPromptService);
  1025.     var buttonFlags = (ps.BUTTON_TITLE_IS_STRING * ps.BUTTON_POS_0) +
  1026.                       (ps.BUTTON_TITLE_CANCEL    * ps.BUTTON_POS_1) +
  1027.                        ps.BUTTON_POS_0_DEFAULT;
  1028.  
  1029.     var checked = {value: false};
  1030.     // confirmEx returns the index of the button that was pressed.  Since "Add"
  1031.     // is button 0, we want to return the negation of that value.
  1032.     var confirm = !ps.confirmEx(null,
  1033.                                 titleMessage,
  1034.                                 dialogMessage,
  1035.                                 buttonFlags,
  1036.                                 addButtonLabel,
  1037.                                 null, null, // button 1 & 2 names not used
  1038.                                 checkboxMessage,
  1039.                                 checked);
  1040.  
  1041.     return {confirmed: confirm, useNow: checked.value};
  1042.   },
  1043.  
  1044.   /**
  1045.    * Handle the successful download of an engine. Initializes the engine and
  1046.    * triggers parsing of the data. The engine is then flushed to disk. Notifies
  1047.    * the search service once initialization is complete.
  1048.    */
  1049.   _onLoad: function SRCH_ENG_onLoad(aBytes, aEngine) {
  1050.     /**
  1051.      * Handle an error during the load of an engine by prompting the user to
  1052.      * notify him that the load failed.
  1053.      */
  1054.     function onError(aErrorString, aTitleString) {
  1055.       if (aEngine._engineToUpdate) {
  1056.         // We're in an update, so just fail quietly
  1057.         LOG("updating " + aEngine._engineToUpdate.name + " failed");
  1058.         return;
  1059.       }
  1060.       var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  1061.                 getService(Ci.nsIStringBundleService);
  1062.  
  1063.       var brandBundle = sbs.createBundle(BRAND_BUNDLE);
  1064.       var brandName = brandBundle.GetStringFromName("brandShortName");
  1065.  
  1066.       var searchBundle = sbs.createBundle(SEARCH_BUNDLE);
  1067.       var msgStringName = aErrorString || "error_loading_engine_msg2";
  1068.       var titleStringName = aTitleString || "error_loading_engine_title";
  1069.       var title = searchBundle.GetStringFromName(titleStringName);
  1070.       var text = searchBundle.formatStringFromName(msgStringName,
  1071.                                                    [brandName, aEngine._location],
  1072.                                                    2);
  1073.  
  1074.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  1075.                getService(Ci.nsIWindowWatcher);
  1076.       ww.getNewPrompter(null).alert(title, text);
  1077.     }
  1078.  
  1079.     if (!aBytes) {
  1080.       onError();
  1081.       return;
  1082.     }
  1083.  
  1084.     var engineToUpdate = null;
  1085.     if (aEngine._engineToUpdate) {
  1086.       engineToUpdate = aEngine._engineToUpdate.wrappedJSObject;
  1087.  
  1088.       // Make this new engine use the old engine's file.
  1089.       aEngine._file = engineToUpdate._file;
  1090.     }
  1091.  
  1092.     switch (aEngine._dataType) {
  1093.       case SEARCH_DATA_XML:
  1094.         var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
  1095.                      createInstance(Ci.nsIDOMParser);
  1096.         var doc = parser.parseFromBuffer(aBytes, aBytes.length, "text/xml");
  1097.         aEngine._data = doc.documentElement;
  1098.         break;
  1099.       case SEARCH_DATA_TEXT:
  1100.         aEngine._data = aBytes;
  1101.         break;
  1102.       default:
  1103.         onError();
  1104.         LOG("_onLoad: Bogus engine _dataType: \"" + this._dataType + "\"");
  1105.         return;
  1106.     }
  1107.  
  1108.     try {
  1109.       // Initialize the engine from the obtained data
  1110.       aEngine._initFromData();
  1111.     } catch (ex) {
  1112.       LOG("_onLoad: Failed to init engine!\n" + ex);
  1113.       // Report an error to the user
  1114.       onError();
  1115.       return;
  1116.     }
  1117.  
  1118.     // Check to see if this is a duplicate engine. If we're confirming the
  1119.     // engine load, then we display a "this is a duplicate engine" prompt,
  1120.     // otherwise we fail silently.
  1121.     if (!engineToUpdate) {
  1122.       var ss = Cc["@mozilla.org/browser/search-service;1"].
  1123.                getService(Ci.nsIBrowserSearchService);
  1124.       if (ss.getEngineByName(aEngine.name)) {
  1125.         if (aEngine._confirm)
  1126.           onError("error_duplicate_engine_msg", "error_invalid_engine_title");
  1127.  
  1128.         LOG("_onLoad: duplicate engine found, bailing");
  1129.         return;
  1130.       }
  1131.     }
  1132.  
  1133.     // If requested, confirm the addition now that we have the title.
  1134.     // This property is only ever true for engines added via
  1135.     // nsIBrowserSearchService::addEngine.
  1136.     if (aEngine._confirm) {
  1137.       var confirmation = aEngine._confirmAddEngine();
  1138.       LOG("_onLoad: confirm is " + confirmation.confirmed +
  1139.           "; useNow is " + confirmation.useNow);
  1140.       if (!confirmation.confirmed)
  1141.         return;
  1142.       aEngine._useNow = confirmation.useNow;
  1143.     }
  1144.  
  1145.     // If we don't yet have a file, get one now. The only case where we would
  1146.     // already have a file is if this is an update and _file was set above.
  1147.     if (!aEngine._file)
  1148.       aEngine._file = getSanitizedFile(aEngine.name);
  1149.  
  1150.     if (engineToUpdate) {
  1151.       // Keep track of the last modified date, so that we can make conditional
  1152.       // requests for future updates.
  1153.       engineMetadataService.setAttr(aEngine, "updatelastmodified",
  1154.                                     (new Date()).toUTCString());
  1155.  
  1156.       // Set the new engine's icon, if it doesn't yet have one.
  1157.       if (!aEngine._iconURI && engineToUpdate._iconURI)
  1158.         aEngine._iconURI = engineToUpdate._iconURI;
  1159.  
  1160.       // Clear the "use now" flag since we don't want to be changing the
  1161.       // current engine for an update.
  1162.       aEngine._useNow = false;
  1163.     }
  1164.  
  1165.     // Write the engine to file
  1166.     aEngine._serializeToFile();
  1167.  
  1168.     // Notify the search service of the sucessful load. It will deal with
  1169.     // updates by checking aEngine._engineToUpdate.
  1170.     notifyAction(aEngine, SEARCH_ENGINE_LOADED);
  1171.   },
  1172.  
  1173.   /**
  1174.    * Sets the .iconURI property of the engine.
  1175.    *
  1176.    *  @param aIconURL
  1177.    *         A URI string pointing to the engine's icon. Must have a http[s],
  1178.    *         ftp, or data scheme. Icons with HTTP[S] or FTP schemes will be
  1179.    *         downloaded and converted to data URIs for storage in the engine
  1180.    *         XML files, if the engine is not readonly.
  1181.    *  @param aIsPreferred
  1182.    *         Whether or not this icon is to be preferred. Preferred icons can
  1183.    *         override non-preferred icons.
  1184.    */
  1185.   _setIcon: function SRCH_ENG_setIcon(aIconURL, aIsPreferred) {
  1186.     // If we already have a preferred icon, and this isn't a preferred icon,
  1187.     // just ignore it.
  1188.     if (this._hasPreferredIcon && !aIsPreferred)
  1189.       return;
  1190.  
  1191.     var uri = makeURI(aIconURL);
  1192.  
  1193.     // Ignore bad URIs
  1194.     if (!uri)
  1195.       return;
  1196.  
  1197.     LOG("_setIcon: Setting icon url \"" + uri.spec + "\" for engine \""
  1198.         + this.name + "\".");
  1199.     // Only accept remote icons from http[s] or ftp
  1200.     switch (uri.scheme) {
  1201.       case "data":
  1202.         this._iconURI = uri;
  1203.         notifyAction(this, SEARCH_ENGINE_CHANGED);
  1204.         this._hasPreferredIcon = aIsPreferred;
  1205.         break;
  1206.       case "http":
  1207.       case "https":
  1208.       case "ftp":
  1209.         // No use downloading the icon if the engine file is read-only
  1210.         if (!this._readOnly) {
  1211.           LOG("_setIcon: Downloading icon: \"" + uri.spec +
  1212.               "\" for engine: \"" + this.name + "\"");
  1213.           var ios = Cc["@mozilla.org/network/io-service;1"].
  1214.                     getService(Ci.nsIIOService);
  1215.           var chan = ios.newChannelFromURI(uri);
  1216.  
  1217.           function iconLoadCallback(aByteArray, aEngine) {
  1218.             // This callback may run after we've already set a preferred icon,
  1219.             // so check again.
  1220.             if (aEngine._hasPreferredIcon && !aIsPreferred)
  1221.               return;
  1222.  
  1223.             if (!aByteArray || aByteArray.length > MAX_ICON_SIZE) {
  1224.               LOG("iconLoadCallback: load failed, or the icon was too large!");
  1225.               return;
  1226.             }
  1227.  
  1228.             var str = btoa(String.fromCharCode.apply(null, aByteArray));
  1229.             aEngine._iconURI = makeURI(ICON_DATAURL_PREFIX + str);
  1230.  
  1231.             // The engine might not have a file yet, if it's being downloaded,
  1232.             // because the request for the engine file itself (_onLoad) may not
  1233.             // yet be complete. In that case, this change will be written to
  1234.             // file when _onLoad is called.
  1235.             if (aEngine._file)
  1236.               aEngine._serializeToFile();
  1237.  
  1238.             notifyAction(aEngine, SEARCH_ENGINE_CHANGED);
  1239.             aEngine._hasPreferredIcon = aIsPreferred;
  1240.           }
  1241.  
  1242.           // If we're currently acting as an "update engine", then the callback
  1243.           // should set the icon on the engine we're updating and not us, since
  1244.           // |this| might be gone by the time the callback runs.
  1245.           var engineToSet = this._engineToUpdate || this;
  1246.  
  1247.           var listener = new loadListener(chan, engineToSet, iconLoadCallback);
  1248.           chan.notificationCallbacks = listener;
  1249.           chan.asyncOpen(listener, null);
  1250.         }
  1251.         break;
  1252.     }
  1253.   },
  1254.  
  1255.   /**
  1256.    * Initialize this Engine object from the collected data.
  1257.    */
  1258.   _initFromData: function SRCH_ENG_initFromData() {
  1259.  
  1260.     ENSURE_WARN(this._data, "Can't init an engine with no data!",
  1261.                 Cr.NS_ERROR_UNEXPECTED);
  1262.  
  1263.     // Find out what type of engine we are
  1264.     switch (this._dataType) {
  1265.       case SEARCH_DATA_XML:
  1266.         if (checkNameSpace(this._data, [MOZSEARCH_LOCALNAME],
  1267.             [MOZSEARCH_NS_10])) {
  1268.  
  1269.           LOG("_init: Initing MozSearch plugin from " + this._location);
  1270.  
  1271.           this._type = SEARCH_TYPE_MOZSEARCH;
  1272.           this._parseAsMozSearch();
  1273.  
  1274.         } else if (checkNameSpace(this._data, [OPENSEARCH_LOCALNAME],
  1275.                                   OPENSEARCH_NAMESPACES)) {
  1276.  
  1277.           LOG("_init: Initing OpenSearch plugin from " + this._location);
  1278.  
  1279.           this._type = SEARCH_TYPE_OPENSEARCH;
  1280.           this._parseAsOpenSearch();
  1281.  
  1282.         } else
  1283.           ENSURE(false, this._location + " is not a valid search plugin.",
  1284.                  Cr.NS_ERROR_FAILURE);
  1285.  
  1286.         break;
  1287.       case SEARCH_DATA_TEXT:
  1288.         LOG("_init: Initing Sherlock plugin from " + this._location);
  1289.  
  1290.         // the only text-based format we support is Sherlock
  1291.         this._type = SEARCH_TYPE_SHERLOCK;
  1292.         this._parseAsSherlock();
  1293.     }
  1294.  
  1295.     // No need to keep a ref to our data (which in some cases can be a document
  1296.     // element) past this point
  1297.     this._data = null;
  1298.   },
  1299.  
  1300.   /**
  1301.    * Initialize this Engine object from a collection of metadata.
  1302.    */
  1303.   _initFromMetadata: function SRCH_ENG_initMetaData(aName, aIconURL, aAlias,
  1304.                                                     aDescription, aMethod,
  1305.                                                     aTemplate) {
  1306.     ENSURE_WARN(!this._readOnly,
  1307.                 "Can't call _initFromMetaData on a readonly engine!",
  1308.                 Cr.NS_ERROR_FAILURE);
  1309.  
  1310.     this._urls.push(new EngineURL("text/html", aMethod, aTemplate));
  1311.  
  1312.     this._name = aName;
  1313.     this._alias = aAlias;
  1314.     this._description = aDescription;
  1315.     this._setIcon(aIconURL, true);
  1316.  
  1317.     this._serializeToFile();
  1318.   },
  1319.  
  1320.   /**
  1321.    * Extracts data from an OpenSearch URL element and creates an EngineURL
  1322.    * object which is then added to the engine's list of URLs.
  1323.    *
  1324.    * @throws NS_ERROR_FAILURE if a URL object could not be created.
  1325.    *
  1326.    * @see http://opensearch.a9.com/spec/1.1/querysyntax/#urltag.
  1327.    * @see EngineURL()
  1328.    */
  1329.   _parseURL: function SRCH_ENG_parseURL(aElement) {
  1330.     var type     = aElement.getAttribute("type");
  1331.     // According to the spec, method is optional, defaulting to "GET" if not
  1332.     // specified
  1333.     var method   = aElement.getAttribute("method") || "GET";
  1334.     var template = aElement.getAttribute("template");
  1335.  
  1336.     try {
  1337.       var url = new EngineURL(type, method, template);
  1338.     } catch (ex) {
  1339.       LOG("_parseURL: failed to add " + template + " as a URL");
  1340.       throw Cr.NS_ERROR_FAILURE;
  1341.     }
  1342.  
  1343.     for (var i = 0; i < aElement.childNodes.length; ++i) {
  1344.       var param = aElement.childNodes[i];
  1345.       if (param.localName == "Param") {
  1346.         try {
  1347.           url.addParam(param.getAttribute("name"), param.getAttribute("value"));
  1348.         } catch (ex) {
  1349.           // Ignore failure
  1350.           LOG("_parseURL: Url element has an invalid param");
  1351.         }
  1352.       } else if (param.localName == "MozParam" &&
  1353.                  // We only support MozParams for default search engines
  1354.                  this._isDefault) {
  1355.         var value;
  1356.         switch (param.getAttribute("condition")) {
  1357.           case "defaultEngine":
  1358.             const defPref = BROWSER_SEARCH_PREF + "defaultenginename";
  1359.             var defaultPrefB = Cc["@mozilla.org/preferences-service;1"].
  1360.                                getService(Ci.nsIPrefService).
  1361.                                getDefaultBranch(null);
  1362.             const nsIPLS = Ci.nsIPrefLocalizedString;
  1363.             var defaultName;
  1364.             try {
  1365.               defaultName = defaultPrefB.getComplexValue(defPref, nsIPLS).data;
  1366.             } catch (ex) {}
  1367.  
  1368.             // If this engine was the default search engine, use the true value
  1369.             if (this.name == defaultName)
  1370.               value = param.getAttribute("trueValue");
  1371.             else
  1372.               value = param.getAttribute("falseValue");
  1373.             url.addParam(param.getAttribute("name"), value);
  1374.             break;
  1375.  
  1376.           case "pref":
  1377.             try {
  1378.               var prefB = Cc["@mozilla.org/preferences-service;1"].
  1379.                           getService(Ci.nsIPrefBranch);
  1380.               value = prefB.getCharPref(BROWSER_SEARCH_PREF + "param." +
  1381.                                         param.getAttribute("pref"));
  1382.               url.addParam(param.getAttribute("name"), value);
  1383.             } catch (e) { }
  1384.             break;
  1385.         }
  1386.       }
  1387.     }
  1388.  
  1389.     this._urls.push(url);
  1390.   },
  1391.  
  1392.   /**
  1393.    * Get the icon from an OpenSearch Image element.
  1394.    * @see http://opensearch.a9.com/spec/1.1/description/#image
  1395.    */
  1396.   _parseImage: function SRCH_ENG_parseImage(aElement) {
  1397.     LOG("_parseImage: Image textContent: \"" + aElement.textContent + "\"");
  1398.     if (aElement.getAttribute("width")  == "16" &&
  1399.         aElement.getAttribute("height") == "16") {
  1400.       this._setIcon(aElement.textContent, true);
  1401.     }
  1402.   },
  1403.  
  1404.   _parseAsMozSearch: function SRCH_ENG_parseAsMoz() {
  1405.     //forward to the OpenSearch parser
  1406.     this._parseAsOpenSearch();
  1407.   },
  1408.  
  1409.   /**
  1410.    * Extract search engine information from the collected data to initialize
  1411.    * the engine object.
  1412.    */
  1413.   _parseAsOpenSearch: function SRCH_ENG_parseAsOS() {
  1414.     var doc = this._data;
  1415.  
  1416.     // The OpenSearch spec sets a default value for the input encoding.
  1417.     this._queryCharset = OS_PARAM_INPUT_ENCODING_DEF;
  1418.  
  1419.     for (var i = 0; i < doc.childNodes.length; ++i) {
  1420.       var child = doc.childNodes[i];
  1421.       switch (child.localName) {
  1422.         case "ShortName":
  1423.           this._name = child.textContent;
  1424.           break;
  1425.         case "Description":
  1426.           this._description = child.textContent;
  1427.           break;
  1428.         case "Url":
  1429.           try {
  1430.             this._parseURL(child);
  1431.           } catch (ex) {
  1432.             // Parsing of the element failed, just skip it.
  1433.           }
  1434.           break;
  1435.         case "Image":
  1436.           this._parseImage(child);
  1437.           break;
  1438.         case "InputEncoding":
  1439.           this._queryCharset = child.textContent.toUpperCase();
  1440.           break;
  1441.  
  1442.         // Non-OpenSearch elements
  1443.         case "Alias":
  1444.           this._alias = child.textContent;
  1445.           break;
  1446.         case "SearchForm":
  1447.           this._searchForm = child.textContent;
  1448.           break;
  1449.         case "UpdateUrl":
  1450.           this._updateURL = child.textContent;
  1451.           break;
  1452.         case "UpdateInterval":
  1453.           this._updateInterval = parseInt(child.textContent);
  1454.           break;
  1455.         case "IconUpdateUrl":
  1456.           this._iconUpdateURL = child.textContent;
  1457.           break;
  1458.       }
  1459.     }
  1460.     ENSURE(this.name && (this._urls.length > 0),
  1461.            "_parseAsOpenSearch: No name, or missing URL!",
  1462.            Cr.NS_ERROR_FAILURE);
  1463.     ENSURE(this.supportsResponseType(URLTYPE_SEARCH_HTML),
  1464.            "_parseAsOpenSearch: No text/html result type!",
  1465.            Cr.NS_ERROR_FAILURE);
  1466.   },
  1467.  
  1468.   /**
  1469.    * Extract search engine information from the collected data to initialize
  1470.    * the engine object.
  1471.    */
  1472.   _parseAsSherlock: function SRCH_ENG_parseAsSherlock() {
  1473.     /**
  1474.      * Trims leading and trailing whitespace from aStr.
  1475.      */
  1476.     function sTrim(aStr) {
  1477.       return aStr.replace(/^\s+/g, "").replace(/\s+$/g, "");
  1478.     }
  1479.  
  1480.     /**
  1481.      * Extracts one Sherlock "section" from aSource. A section is essentially
  1482.      * an HTML element with attributes, but each attribute must be on a new
  1483.      * line, by definition.
  1484.      *
  1485.      * @param aLines
  1486.      *        An array of lines from the sherlock file.
  1487.      * @param aSection
  1488.      *        The name of the section (e.g. "search" or "browser"). This value
  1489.      *        is not case sensitive.
  1490.      * @returns an object whose properties correspond to the section's
  1491.      *          attributes.
  1492.      */
  1493.     function getSection(aLines, aSection) {
  1494.       LOG("_parseAsSherlock::getSection: Sherlock lines:\n" +
  1495.           aLines.join("\n"));
  1496.       var lines = aLines;
  1497.       var startMark = new RegExp("^\\s*<" + aSection.toLowerCase() + "\\s*",
  1498.                                  "gi");
  1499.       var endMark   = /\s*>\s*$/gi;
  1500.  
  1501.       var foundStart = false;
  1502.       var startLine, numberOfLines;
  1503.       // Find the beginning and end of the section
  1504.       for (var i = 0; i < lines.length; i++) {
  1505.         if (foundStart) {
  1506.           if (endMark.test(lines[i])) {
  1507.             numberOfLines = i - startLine;
  1508.             // Remove the end marker
  1509.             lines[i] = lines[i].replace(endMark, "");
  1510.             // If the endmarker was not the only thing on the line, include
  1511.             // this line in the results
  1512.             if (lines[i])
  1513.               numberOfLines++;
  1514.             break;
  1515.           }
  1516.         } else {
  1517.           if (startMark.test(lines[i])) {
  1518.             foundStart = true;
  1519.             // Remove the start marker
  1520.             lines[i] = lines[i].replace(startMark, "");
  1521.             startLine = i;
  1522.             // If the line is empty, don't include it in the result
  1523.             if (!lines[i])
  1524.               startLine++;
  1525.           }
  1526.         }
  1527.       }
  1528.       LOG("_parseAsSherlock::getSection: Start index: " + startLine +
  1529.           "\nNumber of lines: " + numberOfLines);
  1530.       lines = lines.splice(startLine, numberOfLines);
  1531.       LOG("_parseAsSherlock::getSection: Section lines:\n" +
  1532.           lines.join("\n"));
  1533.  
  1534.       var section = {};
  1535.       for (var i = 0; i < lines.length; i++) {
  1536.         var line = sTrim(lines[i]);
  1537.  
  1538.         var els = line.split("=");
  1539.         var name = sTrim(els.shift().toLowerCase());
  1540.         var value = sTrim(els.join("="));
  1541.  
  1542.         if (!name || !value)
  1543.           continue;
  1544.  
  1545.         // Strip leading and trailing whitespace, remove quotes from the
  1546.         // value, and remove any trailing slashes or ">" characters
  1547.         value = value.replace(/^["']/, "")
  1548.                      .replace(/["']\s*[\\\/]?>?\s*$/, "") || "";
  1549.         value = sTrim(value);
  1550.  
  1551.         // Don't clobber existing attributes
  1552.         if (!(name in section))
  1553.           section[name] = value;
  1554.       }
  1555.       return section;
  1556.     }
  1557.  
  1558.     /**
  1559.      * Returns an array of name-value pair arrays representing the Sherlock
  1560.      * file's input elements. User defined inputs return USER_DEFINED
  1561.      * as the value. Elements are returned in the order they appear in the
  1562.      * source file.
  1563.      *
  1564.      *   Example:
  1565.      *      <input name="foo" value="bar">
  1566.      *      <input name="foopy" user>
  1567.      *   Returns:
  1568.      *      [["foo", "bar"], ["foopy", "{searchTerms}"]]
  1569.      *
  1570.      * @param aLines
  1571.      *        An array of lines from the source file.
  1572.      */
  1573.     function getInputs(aLines) {
  1574.  
  1575.       /**
  1576.        * Extracts an attribute value from a given a line of text.
  1577.        *    Example: <input value="foo" name="bar">
  1578.        *      Extracts the string |foo| or |bar| given an input aAttr of
  1579.        *      |value| or |name|.
  1580.        * Attributes may be quoted or unquoted. If unquoted, any whitespace
  1581.        * indicates the end of the attribute value.
  1582.        *    Example: < value=22 33 name=44\334 >
  1583.        *      Returns |22| for "value" and |44\334| for "name".
  1584.        *
  1585.        * @param aAttr
  1586.        *        The name of the attribute for which to obtain the value. This
  1587.        *        value is not case sensitive.
  1588.        * @param aLine
  1589.        *        The line containing the attribute.
  1590.        *
  1591.        * @returns the attribute value, or an empty string if the attribute
  1592.        *          doesn't exist.
  1593.        */
  1594.       function getAttr(aAttr, aLine) {
  1595.         // Used to determine whether an "input" line from a Sherlock file is a
  1596.         // "user defined" input.
  1597.         const userInput = /(\s|["'=])user(\s|[>="'\/\\+]|$)/i;
  1598.  
  1599.         LOG("_parseAsSherlock::getAttr: Getting attr: \"" +
  1600.             aAttr + "\" for line: \"" + aLine + "\"");
  1601.         // We're not case sensitive, but we want to return the attribute value
  1602.         // in its original case, so create a copy of the source
  1603.         var lLine = aLine.toLowerCase();
  1604.         var attr = aAttr.toLowerCase();
  1605.  
  1606.         var attrStart = lLine.search(new RegExp("\\s" + attr, "i"));
  1607.         if (attrStart == -1) {
  1608.  
  1609.           // If this is the "user defined input" (i.e. contains the empty
  1610.           // "user" attribute), return our special keyword
  1611.           if (userInput.test(lLine) && attr == "value") {
  1612.             LOG("_parseAsSherlock::getAttr: Found user input!\nLine:\"" + lLine
  1613.                 + "\"");
  1614.             return USER_DEFINED;
  1615.           }
  1616.           // The attribute doesn't exist - ignore
  1617.           LOG("_parseAsSherlock::getAttr: Failed to find attribute:\nLine:\""
  1618.               + lLine + "\"\nAttr:\"" + attr + "\"");
  1619.           return "";
  1620.         }
  1621.  
  1622.         var valueStart = lLine.indexOf("=", attrStart) + "=".length;
  1623.         if (valueStart == -1)
  1624.           return "";
  1625.  
  1626.         var quoteStart = lLine.indexOf("\"", valueStart);
  1627.         if (quoteStart == -1) {
  1628.  
  1629.           // Unquoted attribute, get the rest of the line, trimmed at the first
  1630.           // sign of whitespace. If the rest of the line is only whitespace,
  1631.           // returns a blank string.
  1632.           return lLine.substr(valueStart).replace(/\s.*$/, "");
  1633.  
  1634.         } else {
  1635.           // Make sure that there's only whitespace between the start of the
  1636.           // value and the first quote. If there is, end the attribute value at
  1637.           // the first sign of whitespace. This prevents us from falling into
  1638.           // the next attribute if this is an unquoted attribute followed by a
  1639.           // quoted attribute.
  1640.           var betweenEqualAndQuote = lLine.substring(valueStart, quoteStart);
  1641.           if (/\S/.test(betweenEqualAndQuote))
  1642.             return lLine.substr(valueStart).replace(/\s.*$/, "");
  1643.  
  1644.           // Adjust the start index to account for the opening quote
  1645.           valueStart = quoteStart + "\"".length;
  1646.           // Find the closing quote
  1647.           valueEnd = lLine.indexOf("\"", valueStart);
  1648.           // If there is no closing quote, just go to the end of the line
  1649.           if (valueEnd == -1)
  1650.             valueEnd = aLine.length;
  1651.         }
  1652.         return aLine.substring(valueStart, valueEnd);
  1653.       }
  1654.  
  1655.       var inputs = [];
  1656.  
  1657.       LOG("_parseAsSherlock::getInputs: Lines:\n" + aLines);
  1658.       // Filter out everything but non-inputs
  1659.       lines = aLines.filter(function (line) {
  1660.         return /^\s*<input/i.test(line);
  1661.       });
  1662.       LOG("_parseAsSherlock::getInputs: Filtered lines:\n" + lines);
  1663.  
  1664.       lines.forEach(function (line) {
  1665.         // Strip leading/trailing whitespace and remove the surrounding markup
  1666.         // ("<input" and ">")
  1667.         line = sTrim(line).replace(/^<input/i, "").replace(/>$/, "");
  1668.  
  1669.         // If this is one of the "directional" inputs (<inputnext>/<inputprev>)
  1670.         const directionalInput = /^(prev|next)/i;
  1671.         if (directionalInput.test(line)) {
  1672.  
  1673.           // Make it look like a normal input by removing "prev" or "next"
  1674.           line = line.replace(directionalInput, "");
  1675.  
  1676.           // If it has a name, give it a dummy value to match previous
  1677.           // nsInternetSearchService behavior
  1678.           if (/name\s*=/i.test(line)) {
  1679.             line += " value=\"0\"";
  1680.           } else
  1681.             return; // Line has no name, skip it
  1682.         }
  1683.  
  1684.         var attrName = getAttr("name", line);
  1685.         var attrValue = getAttr("value", line);
  1686.         LOG("_parseAsSherlock::getInputs: Got input:\nName:\"" + attrName +
  1687.             "\"\nValue:\"" + attrValue + "\"");
  1688.         if (attrValue)
  1689.           inputs.push([attrName, attrValue]);
  1690.       });
  1691.       return inputs;
  1692.     }
  1693.  
  1694.     function err(aErr) {
  1695.       LOG("_parseAsSherlock::err: Sherlock param error:\n" + aErr);
  1696.       throw Cr.NS_ERROR_FAILURE;
  1697.     }
  1698.  
  1699.     // First try converting our byte array using the default Sherlock encoding.
  1700.     // If this fails, or if we find a sourceTextEncoding attribute, we need to
  1701.     // reconvert the byte array using the specified encoding.
  1702.     var sherlockLines, searchSection, sourceTextEncoding, browserSection;
  1703.     try {
  1704.       sherlockLines = sherlockBytesToLines(this._data);
  1705.       searchSection = getSection(sherlockLines, "search");
  1706.       browserSection = getSection(sherlockLines, "browser");
  1707.       sourceTextEncoding = parseInt(searchSection["sourcetextencoding"]);
  1708.       if (sourceTextEncoding) {
  1709.         // Re-convert the bytes using the found sourceTextEncoding
  1710.         sherlockLines = sherlockBytesToLines(this._data, sourceTextEncoding);
  1711.         searchSection = getSection(sherlockLines, "search");
  1712.         browserSection = getSection(sherlockLines, "browser");
  1713.       }
  1714.     } catch (ex) {
  1715.       // The conversion using the default charset failed. Remove any non-ascii
  1716.       // bytes and try to find a sourceTextEncoding.
  1717.       var asciiBytes = this._data.filter(function (n) {return !(0x80 & n);});
  1718.       var asciiString = String.fromCharCode.apply(null, asciiBytes);
  1719.       sherlockLines = asciiString.split(NEW_LINES).filter(isUsefulLine);
  1720.       searchSection = getSection(sherlockLines, "search");
  1721.       sourceTextEncoding = parseInt(searchSection["sourcetextencoding"]);
  1722.       if (sourceTextEncoding) {
  1723.         sherlockLines = sherlockBytesToLines(this._data, sourceTextEncoding);
  1724.         searchSection = getSection(sherlockLines, "search");
  1725.         browserSection = getSection(sherlockLines, "browser");
  1726.       } else
  1727.         ERROR("Couldn't find a working charset", Cr.NS_ERROR_FAILURE);
  1728.     }
  1729.  
  1730.     LOG("_parseAsSherlock: Search section:\n" + searchSection.toSource());
  1731.  
  1732.     this._name = searchSection["name"] || err("Missing name!");
  1733.     this._description = searchSection["description"] || "";
  1734.     this._queryCharset = searchSection["querycharset"] ||
  1735.                          queryCharsetFromCode(searchSection["queryencoding"]);
  1736.     this._searchForm = searchSection["searchform"];
  1737.  
  1738.     this._updateInterval = parseInt(browserSection["updatecheckdays"]);
  1739.  
  1740.     this._updateURL = browserSection["update"];
  1741.     this._iconUpdateURL = browserSection["updateicon"];
  1742.  
  1743.     var method = (searchSection["method"] || "GET").toUpperCase();
  1744.     var template = searchSection["action"] || err("Missing action!");
  1745.  
  1746.     var inputs = getInputs(sherlockLines);
  1747.     LOG("_parseAsSherlock: Inputs:\n" + inputs.toSource());
  1748.  
  1749.     var url = null;
  1750.  
  1751.     if (method == "GET") {
  1752.       // Here's how we construct the input string:
  1753.       // <input> is first:  Name Attr:  Prefix      Data           Example:
  1754.       // YES                EMPTY       None        <value>        TEMPLATE<value>
  1755.       // YES                NON-EMPTY   ?           <name>=<value> TEMPLATE?<name>=<value>
  1756.       // NO                 EMPTY       ------------- <ignored> --------------
  1757.       // NO                 NON-EMPTY   &           <name>=<value> TEMPLATE?<n1>=<v1>&<n2>=<v2>
  1758.       for (var i = 0; i < inputs.length; i++) {
  1759.         var name  = inputs[i][0];
  1760.         var value = inputs[i][1];
  1761.         if (i==0) {
  1762.           if (name == "")
  1763.             template += USER_DEFINED;
  1764.           else
  1765.             template += "?" + name + "=" + value;
  1766.         } else if (name != "")
  1767.           template += "&" + name + "=" + value;
  1768.       }
  1769.       url = new EngineURL("text/html", method, template);
  1770.  
  1771.     } else if (method == "POST") {
  1772.       // Create the URL object and just add the parameters directly
  1773.       url = new EngineURL("text/html", method, template);
  1774.       for (var i = 0; i < inputs.length; i++) {
  1775.         var name  = inputs[i][0];
  1776.         var value = inputs[i][1];
  1777.         if (name)
  1778.           url.addParam(name, value);
  1779.       }
  1780.     } else
  1781.       err("Invalid method!");
  1782.  
  1783.     this._urls.push(url);
  1784.   },
  1785.  
  1786.   /**
  1787.    * Returns an XML document object containing the search plugin information,
  1788.    * which can later be used to reload the engine.
  1789.    */
  1790.   _serializeToElement: function SRCH_ENG_serializeToEl() {
  1791.     function appendTextNode(aNameSpace, aLocalName, aValue) {
  1792.       if (!aValue)
  1793.         return null;
  1794.       var node = doc.createElementNS(aNameSpace, aLocalName);
  1795.       node.appendChild(doc.createTextNode(aValue));
  1796.       docElem.appendChild(node);
  1797.       docElem.appendChild(doc.createTextNode("\n"));
  1798.       return node;
  1799.     }
  1800.  
  1801.     var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
  1802.                  createInstance(Ci.nsIDOMParser);
  1803.  
  1804.     var doc = parser.parseFromString(EMPTY_DOC, "text/xml");
  1805.     docElem = doc.documentElement;
  1806.  
  1807.     docElem.appendChild(doc.createTextNode("\n"));
  1808.  
  1809.     appendTextNode(OPENSEARCH_NS_11, "ShortName", this.name);
  1810.     appendTextNode(OPENSEARCH_NS_11, "Description", this._description);
  1811.     appendTextNode(OPENSEARCH_NS_11, "InputEncoding", this._queryCharset);
  1812.  
  1813.     if (this._iconURI) {
  1814.       var imageNode = appendTextNode(OPENSEARCH_NS_11, "Image",
  1815.                                      this._iconURI.spec);
  1816.       if (imageNode) {
  1817.         imageNode.setAttribute("width", "16");
  1818.         imageNode.setAttribute("height", "16");
  1819.       }
  1820.     }
  1821.  
  1822.     appendTextNode(MOZSEARCH_NS_10, "Alias", this.alias);
  1823.     appendTextNode(MOZSEARCH_NS_10, "UpdateInterval", this._updateInterval);
  1824.     appendTextNode(MOZSEARCH_NS_10, "UpdateUrl", this._updateURL);
  1825.     appendTextNode(MOZSEARCH_NS_10, "IconUpdateUrl", this._iconUpdateURL);
  1826.     appendTextNode(MOZSEARCH_NS_10, "SearchForm", this._searchForm);
  1827.  
  1828.     for (var i = 0; i < this._urls.length; ++i)
  1829.       this._urls[i]._serializeToElement(doc, docElem);
  1830.     docElem.appendChild(doc.createTextNode("\n"));
  1831.  
  1832.     return doc;
  1833.   },
  1834.  
  1835.   _lazySerializeToFile: function SRCH_ENG_serializeToFile() {
  1836.     if (this._serializeTimer) {
  1837.       // Reset the timer
  1838.       this._serializeTimer.delay = LAZY_SERIALIZE_DELAY;
  1839.     } else {
  1840.       this._serializeTimer = Cc["@mozilla.org/timer;1"].
  1841.                              createInstance(Ci.nsITimer);
  1842.       var timerCallback = {
  1843.         self: this,
  1844.         notify: function SRCH_ENG_notify(aTimer) {
  1845.           try {
  1846.             this.self._serializeToFile();
  1847.           } catch (ex) {
  1848.             LOG("Serialization from timer callback failed:\n" + ex);
  1849.           }
  1850.           this.self._serializeTimer = null;
  1851.         }
  1852.       };
  1853.       this._serializeTimer.initWithCallback(timerCallback,
  1854.                                             LAZY_SERIALIZE_DELAY,
  1855.                                             Ci.nsITimer.TYPE_ONE_SHOT);
  1856.     }
  1857.   },
  1858.  
  1859.   /**
  1860.    * Serializes the engine object to file.
  1861.    */
  1862.   _serializeToFile: function SRCH_ENG_serializeToFile() {
  1863.     var file = this._file;
  1864.     ENSURE_WARN(!this._readOnly, "Can't serialize a read only engine!",
  1865.                 Cr.NS_ERROR_FAILURE);
  1866.     ENSURE_WARN(file && file.exists(), "Can't serialize: file doesn't exist!",
  1867.                 Cr.NS_ERROR_UNEXPECTED);
  1868.  
  1869.     var fos = Cc["@mozilla.org/network/safe-file-output-stream;1"].
  1870.               createInstance(Ci.nsIFileOutputStream);
  1871.  
  1872.     // Serialize the engine first - we don't want to overwrite a good file
  1873.     // if this somehow fails.
  1874.     doc = this._serializeToElement();
  1875.  
  1876.     fos.init(file, (MODE_WRONLY | MODE_TRUNCATE), PERMS_FILE, 0);
  1877.  
  1878.     try {
  1879.       var serializer = Cc["@mozilla.org/xmlextras/xmlserializer;1"].
  1880.                        createInstance(Ci.nsIDOMSerializer);
  1881.       serializer.serializeToStream(doc.documentElement, fos, null);
  1882.     } catch (e) {
  1883.       LOG("_serializeToFile: Error serializing engine:\n" + e);
  1884.     }
  1885.  
  1886.     closeSafeOutputStream(fos);
  1887.   },
  1888.  
  1889.   /**
  1890.    * Remove the engine's file from disk. The search service calls this once it
  1891.    * removes the engine from its internal store. This function will throw if
  1892.    * the file cannot be removed.
  1893.    */
  1894.   _remove: function SRCH_ENG_remove() {
  1895.     ENSURE(!this._readOnly, "Can't remove read only engine!",
  1896.            Cr.NS_ERROR_FAILURE);
  1897.     ENSURE(this._file && this._file.exists(),
  1898.            "Can't remove engine: file doesn't exist!",
  1899.            Cr.NS_ERROR_FILE_NOT_FOUND);
  1900.  
  1901.     this._file.remove(false);
  1902.   },
  1903.  
  1904.   // nsISearchEngine
  1905.   get alias() {
  1906.     if (this._alias === null)
  1907.       this._alias = engineMetadataService.getAttr(this, "alias");
  1908.  
  1909.     return this._alias;
  1910.   },
  1911.   set alias(val) {
  1912.     this._alias = val;
  1913.     engineMetadataService.setAttr(this, "alias", val);
  1914.     notifyAction(this, SEARCH_ENGINE_CHANGED);
  1915.   },
  1916.  
  1917.   get description() {
  1918.     return this._description;
  1919.   },
  1920.  
  1921.   get hidden() {
  1922.     if (this._hidden === null)
  1923.       this._hidden = engineMetadataService.getAttr(this, "hidden");
  1924.     return this._hidden;
  1925.   },
  1926.   set hidden(val) {
  1927.     var value = !!val;
  1928.     if (value != this._hidden) {
  1929.       this._hidden = value;
  1930.       engineMetadataService.setAttr(this, "hidden", value);
  1931.       notifyAction(this, SEARCH_ENGINE_CHANGED);
  1932.     }
  1933.   },
  1934.  
  1935.   get iconURI() {
  1936.     return this._iconURI;
  1937.   },
  1938.  
  1939.   get _iconURL() {
  1940.     if (!this._iconURI)
  1941.       return "";
  1942.     return this._iconURI.spec;
  1943.   },
  1944.  
  1945.   // Where the engine is being loaded from: will return the URI's spec if the
  1946.   // engine is being downloaded and does not yet have a file. This is only used
  1947.   // for logging.
  1948.   get _location() {
  1949.     if (this._file)
  1950.       return this._file.path;
  1951.  
  1952.     if (this._uri)
  1953.       return this._uri.spec;
  1954.  
  1955.     return "";
  1956.   },
  1957.  
  1958.   // The file that the plugin is loaded from is a unique identifier for it.  We
  1959.   // use this as the identifier to store data in the sqlite database
  1960.   get _id() {
  1961.     ENSURE_WARN(this._file, "No _file for id!", Cr.NS_ERROR_FAILURE);
  1962.  
  1963.     if (this._isInProfile)
  1964.       return "[profile]/" + this._file.leafName;
  1965.  
  1966.     if (this._isInAppDir)
  1967.       return "[app]/" + this._file.leafName;
  1968.  
  1969.     // We're not in the profile or appdir, so this must be an extension-shipped
  1970.     // plugin. Use the full path.
  1971.     return this._file.path;
  1972.   },
  1973.  
  1974.   get _installLocation() {
  1975.     ENSURE_WARN(this._file && this._file.exists(),
  1976.                 "_installLocation: engine has no file!",
  1977.                 Cr.NS_ERROR_FAILURE);
  1978.  
  1979.     if (this.__installLocation === null) {
  1980.       if (this._file.parent.equals(getDir(NS_APP_SEARCH_DIR)))
  1981.         this.__installLocation = SEARCH_APP_DIR;
  1982.       else if (this._file.parent.equals(getDir(NS_APP_USER_SEARCH_DIR)))
  1983.         this.__installLocation = SEARCH_PROFILE_DIR;
  1984.       else
  1985.         this.__installLocation = SEARCH_IN_EXTENSION;
  1986.     }
  1987.  
  1988.     return this.__installLocation;
  1989.   },
  1990.  
  1991.   get _isInAppDir() {
  1992.     return this._installLocation == SEARCH_APP_DIR;
  1993.   },
  1994.   get _isInProfile() {
  1995.     return this._installLocation == SEARCH_PROFILE_DIR;
  1996.   },
  1997.  
  1998.   get _isDefault() {
  1999.     // For now, our concept of a "default engine" is "one that is not in the
  2000.     // user's profile directory", which is currently equivalent to "is app- or
  2001.     // extension-shipped".
  2002.     return !this._isInProfile;
  2003.   },
  2004.  
  2005.   get _hasUpdates() {
  2006.     // Whether or not the engine has an update URL
  2007.     return !!(this._updateURL || this._iconUpdateURL);
  2008.   },
  2009.  
  2010.   get name() {
  2011.     return this._name;
  2012.   },
  2013.  
  2014.   get type() {
  2015.     return this._type;
  2016.   },
  2017.  
  2018.   get searchForm() {
  2019.     if (!this._searchForm) {
  2020.       // No searchForm specified in the engine definition file, use the prePath
  2021.       // (e.g. https://foo.com for https://foo.com/search.php?q=bar).
  2022.       var htmlUrl = this._getURLOfType(URLTYPE_SEARCH_HTML);
  2023.       ENSURE_WARN(htmlUrl, "Engine has no HTML URL!", Cr.NS_ERROR_UNEXPECTED);
  2024.       this._searchForm = makeURI(htmlUrl.template).prePath;
  2025.     }
  2026.  
  2027.     return this._searchForm;
  2028.   },
  2029.  
  2030.   get queryCharset() {
  2031.     if (this._queryCharset)
  2032.       return this._queryCharset;
  2033.     return this._queryCharset = queryCharsetFromCode(/* get the default */);
  2034.   },
  2035.  
  2036.   // from nsISearchEngine
  2037.   addParam: function SRCH_ENG_addParam(aName, aValue, aResponseType) {
  2038.     ENSURE_ARG(aName && (aValue != null),
  2039.                "missing name or value for nsISearchEngine::addParam!");
  2040.     ENSURE_WARN(!this._readOnly,
  2041.                 "called nsISearchEngine::addParam on a read-only engine!",
  2042.                 Cr.NS_ERROR_FAILURE);
  2043.     if (!aResponseType)
  2044.       aResponseType = URLTYPE_SEARCH_HTML;
  2045.  
  2046.     var url = this._getURLOfType(aResponseType);
  2047.  
  2048.     ENSURE(url, "Engine object has no URL for response type " + aResponseType,
  2049.            Cr.NS_ERROR_FAILURE);
  2050.  
  2051.     url.addParam(aName, aValue);
  2052.  
  2053.     // Serialize the changes to file lazily
  2054.     this._lazySerializeToFile();
  2055.   },
  2056.  
  2057.   // from nsISearchEngine
  2058.   getSubmission: function SRCH_ENG_getSubmission(aData, aResponseType) {
  2059.     if (!aResponseType)
  2060.       aResponseType = URLTYPE_SEARCH_HTML;
  2061.  
  2062.     var url = this._getURLOfType(aResponseType);
  2063.  
  2064.     if (!url)
  2065.       return null;
  2066.  
  2067.     if (!aData) {
  2068.       // Return a dummy submission object with our searchForm attribute
  2069.       return new Submission(makeURI(this.searchForm), null);
  2070.     }
  2071.  
  2072.     LOG("getSubmission: In data: \"" + aData + "\"");
  2073.     var textToSubURI = Cc["@mozilla.org/intl/texttosuburi;1"].
  2074.                        getService(Ci.nsITextToSubURI);
  2075.     var data = "";
  2076.     try {
  2077.       data = textToSubURI.ConvertAndEscape(this.queryCharset, aData);
  2078.     } catch (ex) {
  2079.       LOG("getSubmission: Falling back to default queryCharset!");
  2080.       data = textToSubURI.ConvertAndEscape(DEFAULT_QUERY_CHARSET, aData);
  2081.     }
  2082.     LOG("getSubmission: Out data: \"" + data + "\"");
  2083.     return url.getSubmission(data, this);
  2084.   },
  2085.  
  2086.   // from nsISearchEngine
  2087.   supportsResponseType: function SRCH_ENG_supportsResponseType(type) {
  2088.     return (this._getURLOfType(type) != null);
  2089.   },
  2090.  
  2091.   // nsISupports
  2092.   QueryInterface: function SRCH_ENG_QI(aIID) {
  2093.     if (aIID.equals(Ci.nsISearchEngine) ||
  2094.         aIID.equals(Ci.nsISupports))
  2095.       return this;
  2096.     throw Cr.NS_ERROR_NO_INTERFACE;
  2097.   },
  2098.  
  2099.   get wrappedJSObject() {
  2100.     return this;
  2101.   }
  2102.  
  2103. };
  2104.  
  2105. // nsISearchSubmission
  2106. function Submission(aURI, aPostData) {
  2107.   this._uri = aURI;
  2108.   this._postData = aPostData;
  2109. }
  2110. Submission.prototype = {
  2111.   get uri() {
  2112.     return this._uri;
  2113.   },
  2114.   get postData() {
  2115.     return this._postData;
  2116.   },
  2117.   QueryInterface: function SRCH_SUBM_QI(aIID) {
  2118.     if (aIID.equals(Ci.nsISearchSubmission) ||
  2119.         aIID.equals(Ci.nsISupports))
  2120.       return this;
  2121.     throw Cr.NS_ERROR_NO_INTERFACE;
  2122.   }
  2123. }
  2124.  
  2125. // nsIBrowserSearchService
  2126. function SearchService() {
  2127.   this._init();
  2128. }
  2129. SearchService.prototype = {
  2130.   _engines: { },
  2131.   _sortedEngines: null,
  2132.   // Whether or not we need to write the order of engines on shutdown. This
  2133.   // needs to happen anytime _sortedEngines is modified after initial startup. 
  2134.   _needToSetOrderPrefs: false,
  2135.  
  2136.   _init: function() {
  2137.     engineMetadataService.init();
  2138.     engineUpdateService.init();
  2139.  
  2140.     this._addObservers();
  2141.  
  2142.     var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
  2143.                       getService(Ci.nsIProperties);
  2144.     var locations = fileLocator.get(NS_APP_SEARCH_DIR_LIST,
  2145.                                     Ci.nsISimpleEnumerator);
  2146.  
  2147.     while (locations.hasMoreElements()) {
  2148.       var location = locations.getNext().QueryInterface(Ci.nsIFile);
  2149.       this._loadEngines(location);
  2150.     }
  2151.  
  2152.     // Now that all engines are loaded, build the sorted engine list
  2153.     this._buildSortedEngineList();
  2154.  
  2155.     selectedEngineName = getLocalizedPref(BROWSER_SEARCH_PREF +
  2156.                                           "selectedEngine");
  2157.     this._currentEngine = this.getEngineByName(selectedEngineName) ||
  2158.                           this.defaultEngine;
  2159.   },
  2160.  
  2161.   _addEngineToStore: function SRCH_SVC_addEngineToStore(aEngine) {
  2162.     LOG("_addEngineToStore: Adding engine: \"" + aEngine.name + "\"");
  2163.  
  2164.     // See if there is an existing engine with the same name. However, if this
  2165.     // engine is updating another engine, it's allowed to have the same name.
  2166.     var hasSameNameAsUpdate = (aEngine._engineToUpdate &&
  2167.                                aEngine.name == aEngine._engineToUpdate.name);
  2168.     if (aEngine.name in this._engines && !hasSameNameAsUpdate) {
  2169.       LOG("_addEngineToStore: Duplicate engine found, aborting!");
  2170.       return;
  2171.     }
  2172.  
  2173.     if (aEngine._engineToUpdate) {
  2174.       // We need to replace engineToUpdate with the engine that just loaded.
  2175.       var oldEngine = aEngine._engineToUpdate;
  2176.  
  2177.       // Remove the old engine from the hash, since it's keyed by name, and our
  2178.       // name might change (the update might have a new name).
  2179.       delete this._engines[oldEngine.name];
  2180.  
  2181.       // Hack: we want to replace the old engine with the new one, but since
  2182.       // people may be holding refs to the nsISearchEngine objects themselves,
  2183.       // we'll just copy over all "private" properties (those without a getter
  2184.       // or setter) from one object to the other.
  2185.       for (var p in aEngine) {
  2186.         if (!(aEngine.__lookupGetter__(p) || aEngine.__lookupSetter__(p)))
  2187.           oldEngine[p] = aEngine[p];
  2188.       }
  2189.       aEngine = oldEngine;
  2190.       aEngine._engineToUpdate = null;
  2191.  
  2192.       // Add the engine back
  2193.       this._engines[aEngine.name] = aEngine;
  2194.       notifyAction(aEngine, SEARCH_ENGINE_CHANGED);
  2195.     } else {
  2196.       // Not an update, just add the new engine.
  2197.       this._engines[aEngine.name] = aEngine;
  2198.       // Only add the engine to the list of sorted engines if the initial list
  2199.       // has already been built (i.e. if this._sortedEngines is non-null). If
  2200.       // it hasn't, we're still loading engines from disk, and will build the
  2201.       // sorted engine list when that initial loading is done.
  2202.       if (this._sortedEngines) {
  2203.         this._sortedEngines.push(aEngine);
  2204.         this._needToSetOrderPrefs = true;
  2205.       }
  2206.       notifyAction(aEngine, SEARCH_ENGINE_ADDED);
  2207.     }
  2208.  
  2209.     if (aEngine._hasUpdates) {
  2210.       // Schedule the engine's next update, if it isn't already.
  2211.       if (!engineMetadataService.getAttr(aEngine, "updateexpir"))
  2212.         engineUpdateService.scheduleNextUpdate(aEngine);
  2213.   
  2214.       // We need to save the engine's _dataType, if this is the first time the
  2215.       // engine is added to the dataStore, since ._dataType isn't persisted
  2216.       // and will change on the next startup (since the engine will then be
  2217.       // XML). We need this so that we know how to load any future updates from
  2218.       // this engine.
  2219.       if (!engineMetadataService.getAttr(aEngine, "updatedatatype"))
  2220.         engineMetadataService.setAttr(aEngine, "updatedatatype",
  2221.                                       aEngine._dataType);
  2222.     }
  2223.   },
  2224.  
  2225.   _loadEngines: function SRCH_SVC_loadEngines(aDir) {
  2226.     LOG("_loadEngines: Searching in " + aDir.path + " for search engines.");
  2227.  
  2228.     // Check whether aDir is the user profile dir
  2229.     var isInProfile = aDir.equals(getDir(NS_APP_USER_SEARCH_DIR));
  2230.  
  2231.     var files = aDir.directoryEntries
  2232.                     .QueryInterface(Ci.nsIDirectoryEnumerator);
  2233.     var ios = Cc["@mozilla.org/network/io-service;1"].
  2234.               getService(Ci.nsIIOService);
  2235.  
  2236.     while (files.hasMoreElements()) {
  2237.       var file = files.nextFile;
  2238.  
  2239.       // Ignore hidden and empty files, and directories
  2240.       if (!file.isFile() || file.fileSize == 0 || file.isHidden())
  2241.         continue;
  2242.  
  2243.       var fileURL = ios.newFileURI(file).QueryInterface(Ci.nsIURL);
  2244.       var fileExtension = fileURL.fileExtension.toLowerCase();
  2245.       var isWritable = isInProfile && file.isWritable();
  2246.  
  2247.       var dataType;
  2248.       switch (fileExtension) {
  2249.         case XML_FILE_EXT:
  2250.           dataType = SEARCH_DATA_XML;
  2251.           break;
  2252.         case SHERLOCK_FILE_EXT:
  2253.           dataType = SEARCH_DATA_TEXT;
  2254.           break;
  2255.         default:
  2256.           // Not an engine
  2257.           continue;
  2258.       }
  2259.  
  2260.       var addedEngine = null;
  2261.       try {
  2262.         addedEngine = new Engine(file, dataType, !isWritable);
  2263.         addedEngine._initFromFile();
  2264.       } catch (ex) {
  2265.         LOG("_loadEngines: Failed to load " + file.path + "!\n" + ex);
  2266.         continue;
  2267.       }
  2268.  
  2269.       if (fileExtension == SHERLOCK_FILE_EXT) {
  2270.         if (isWritable) {
  2271.           try {
  2272.             this._convertSherlockFile(addedEngine, fileURL.fileBaseName);
  2273.           } catch (ex) {
  2274.             LOG("_loadEngines: Failed to convert: " + fileURL.path + "\n" + ex);
  2275.             // The engine couldn't be converted, mark it as read-only
  2276.             addedEngine._readOnly = true;
  2277.           }
  2278.         }
  2279.  
  2280.         // If the engine still doesn't have an icon, see if we can find one
  2281.         if (!addedEngine._iconURI) {
  2282.           var icon = this._findSherlockIcon(file, fileURL.fileBaseName);
  2283.           if (icon)
  2284.             addedEngine._iconURI = ios.newFileURI(icon);
  2285.         }
  2286.       }
  2287.  
  2288.       this._addEngineToStore(addedEngine);
  2289.     }
  2290.   },
  2291.  
  2292.   _saveSortedEngineList: function SRCH_SVC_saveSortedEngineList() {
  2293.     // We only need to write the prefs. if something has changed.
  2294.     if (!this._needToSetOrderPrefs)
  2295.       return;
  2296.  
  2297.     // Set the useDB pref to indicate that from now on we should use the order
  2298.     // information stored in the database.
  2299.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  2300.                 getService(Ci.nsIPrefBranch);
  2301.     prefB.setBoolPref(BROWSER_SEARCH_PREF + "useDBForOrder", true);
  2302.  
  2303.     var engines = this._getSortedEngines(true);
  2304.     var values = [];
  2305.     var names = [];
  2306.  
  2307.     for (var i = 0; i < engines.length; ++i) {
  2308.       names[i] = "order";
  2309.       values[i] = i + 1;
  2310.     }
  2311.  
  2312.     engineMetadataService.setAttrs(engines, names, values);
  2313.   },
  2314.  
  2315.   _buildSortedEngineList: function SRCH_SVC_buildSortedEngineList() {
  2316.     var addedEngines = { };
  2317.     this._sortedEngines = [];
  2318.     var engine;
  2319.  
  2320.     // If the user has specified a custom engine order, read the order
  2321.     // information from the engineMetadataService instead of the default
  2322.     // prefs.
  2323.     if (getBoolPref(BROWSER_SEARCH_PREF + "useDBForOrder", false)) {
  2324.       for each (engine in this._engines) {
  2325.         var orderNumber = engineMetadataService.getAttr(engine, "order");
  2326.  
  2327.         // Since the DB isn't regularly cleared, and engine files may disappear
  2328.         // without us knowing, we may already have an engine in this slot. If
  2329.         // that happens, we just skip it - it will be added later on as an
  2330.         // unsorted engine. This problem will sort itself out when we call
  2331.         // _saveSortedEngineList at shutdown.
  2332.         if (orderNumber && !this._sortedEngines[orderNumber-1]) {
  2333.           this._sortedEngines[orderNumber-1] = engine;
  2334.           addedEngines[engine.name] = engine;
  2335.         } else {
  2336.           // We need to call _saveSortedEngines so this gets sorted out.
  2337.           this._needToSetOrderPrefs = true;
  2338.         }
  2339.       }
  2340.  
  2341.       // Filter out any nulls for engines that may have been removed
  2342.       var filteredEngines = this._sortedEngines.filter(function(a) { return !!a; });
  2343.       if (this._sortedEngines.length != filteredEngines.length)
  2344.         this._needToSetOrderPrefs = true;
  2345.       this._sortedEngines = filteredEngines;
  2346.  
  2347.     } else {
  2348.       // The DB isn't being used, so just read the engine order from the prefs
  2349.       var i = 0;
  2350.       var engineName;
  2351.       var prefName;
  2352.  
  2353.       try {
  2354.         var prefB = Cc["@mozilla.org/preferences-service;1"].
  2355.                     getService(Ci.nsIPrefBranch);
  2356.         var extras =
  2357.           prefB.getChildList(BROWSER_SEARCH_PREF + "order.extra.", { });
  2358.  
  2359.         for each (prefName in extras) {
  2360.           engineName = prefB.getCharPref(prefName);
  2361.  
  2362.           engine = this._engines[engineName];
  2363.           if (!engine || engine.name in addedEngines)
  2364.             continue;
  2365.  
  2366.           this._sortedEngines.push(engine);
  2367.           addedEngines[engine.name] = engine;
  2368.         }
  2369.       }
  2370.       catch (e) { }
  2371.  
  2372.       while (true) {
  2373.         engineName = getLocalizedPref(BROWSER_SEARCH_PREF + "order." + (++i));
  2374.         if (!engineName)
  2375.           break;
  2376.  
  2377.         engine = this._engines[engineName];
  2378.         if (!engine || engine.name in addedEngines)
  2379.           continue;
  2380.         
  2381.         this._sortedEngines.push(engine);
  2382.         addedEngines[engine.name] = engine;
  2383.       }
  2384.     }
  2385.  
  2386.     // Array for the remaining engines, alphabetically sorted
  2387.     var alphaEngines = [];
  2388.  
  2389.     for each (engine in this._engines) {
  2390.       if (!(engine.name in addedEngines))
  2391.         alphaEngines.push(this._engines[engine.name]);
  2392.     }
  2393.     alphaEngines = alphaEngines.sort(function (a, b) {
  2394.                                        return a.name.localeCompare(b.name);
  2395.                                      });
  2396.     this._sortedEngines = this._sortedEngines.concat(alphaEngines);
  2397.   },
  2398.  
  2399.   /**
  2400.    * Converts a Sherlock file and its icon into the custom XML format used by
  2401.    * the Search Service. Saves the engine's icon (if present) into the XML as a
  2402.    * data: URI and changes the extension of the source file from ".src" to
  2403.    * ".xml". The engine data is then written to the file as XML.
  2404.    * @param aEngine
  2405.    *        The Engine object that needs to be converted.
  2406.    * @param aBaseName
  2407.    *        The basename of the Sherlock file.
  2408.    *          Example: "foo" for file "foo.src".
  2409.    *
  2410.    * @throws NS_ERROR_FAILURE if the file could not be converted.
  2411.    *
  2412.    * @see nsIURL::fileBaseName
  2413.    */
  2414.   _convertSherlockFile: function SRCH_SVC_convertSherlock(aEngine, aBaseName) {
  2415.     var oldSherlockFile = aEngine._file;
  2416.  
  2417.     // Back up the old file
  2418.     try {
  2419.       var backupDir = oldSherlockFile.parent;
  2420.       backupDir.append("searchplugins-backup");
  2421.  
  2422.       if (!backupDir.exists())
  2423.         backupDir.create(Ci.nsIFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  2424.  
  2425.       oldSherlockFile.copyTo(backupDir, null);
  2426.     } catch (ex) {
  2427.       // Just bail. Engines that can't be backed up won't be converted, but
  2428.       // engines that aren't converted are loaded as readonly.
  2429.       LOG("_convertSherlockFile: Couldn't back up " + oldSherlockFile.path +
  2430.           ":\n" + ex);
  2431.       throw Cr.NS_ERROR_FAILURE;
  2432.     }
  2433.  
  2434.     // Rename the file, but don't clobber existing files
  2435.     var newXMLFile = oldSherlockFile.parent.clone();
  2436.     newXMLFile.append(aBaseName + "." + XML_FILE_EXT);
  2437.  
  2438.     if (newXMLFile.exists()) {
  2439.       // There is an existing file with this name, create a unique file
  2440.       newXMLFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, PERMS_FILE);
  2441.     }
  2442.  
  2443.     // Rename the .src file to .xml
  2444.     oldSherlockFile.moveTo(null, newXMLFile.leafName);
  2445.  
  2446.     aEngine._file = newXMLFile;
  2447.  
  2448.     // Write the converted engine to disk
  2449.     aEngine._serializeToFile();
  2450.  
  2451.     // Update the engine's _type.
  2452.     aEngine._type = SEARCH_TYPE_MOZSEARCH;
  2453.  
  2454.     // See if it has a corresponding icon
  2455.     try {
  2456.       var icon = this._findSherlockIcon(aEngine._file, aBaseName);
  2457.       if (icon && icon.fileSize < MAX_ICON_SIZE) {
  2458.         // Use this as the engine's icon
  2459.         var bStream = Cc["@mozilla.org/binaryinputstream;1"].
  2460.                         createInstance(Ci.nsIBinaryInputStream);
  2461.         var fileInStream = Cc["@mozilla.org/network/file-input-stream;1"].
  2462.                            createInstance(Ci.nsIFileInputStream);
  2463.  
  2464.         fileInStream.init(icon, MODE_RDONLY, PERMS_FILE, 0);
  2465.         bStream.setInputStream(fileInStream);
  2466.  
  2467.         var bytes = [];
  2468.         while (bStream.available() != 0)
  2469.           bytes = bytes.concat(bStream.readByteArray(bStream.available()));
  2470.         bStream.close();
  2471.  
  2472.         // Convert the byte array to a base64-encoded string
  2473.         var str = b64(bytes);
  2474.  
  2475.         aEngine._iconURI = makeURI(ICON_DATAURL_PREFIX + str);
  2476.         LOG("_importSherlockEngine: Set sherlock iconURI to: \"" +
  2477.             aEngine._iconURL + "\"");
  2478.  
  2479.         // Write the engine to disk to save changes
  2480.         aEngine._serializeToFile();
  2481.  
  2482.         // Delete the icon now that we're sure everything's been saved
  2483.         icon.remove(false);
  2484.       }
  2485.     } catch (ex) { LOG("_convertSherlockFile: Error setting icon:\n" + ex); }
  2486.   },
  2487.  
  2488.   /**
  2489.    * Finds an icon associated to a given Sherlock file. Searches the provided
  2490.    * file's parent directory looking for files with the same base name and one
  2491.    * of the file extensions in SHERLOCK_ICON_EXTENSIONS.
  2492.    * @param aEngineFile
  2493.    *        The Sherlock plugin file.
  2494.    * @param aBaseName
  2495.    *        The basename of the Sherlock file.
  2496.    *          Example: "foo" for file "foo.src".
  2497.    * @see nsIURL::fileBaseName
  2498.    */
  2499.   _findSherlockIcon: function SRCH_SVC_findSherlock(aEngineFile, aBaseName) {
  2500.     for (var i = 0; i < SHERLOCK_ICON_EXTENSIONS.length; i++) {
  2501.       var icon = aEngineFile.parent.clone();
  2502.       icon.append(aBaseName + SHERLOCK_ICON_EXTENSIONS[i]);
  2503.       if (icon.exists() && icon.isFile())
  2504.         return icon;
  2505.     }
  2506.     return null;
  2507.   },
  2508.  
  2509.   /**
  2510.    * Get a sorted array of engines.
  2511.    * @param aWithHidden
  2512.    *        True if hidden plugins should be included in the result.
  2513.    */
  2514.   _getSortedEngines: function SRCH_SVC_getSorted(aWithHidden) {
  2515.     if (aWithHidden)
  2516.       return this._sortedEngines;
  2517.  
  2518.     return this._sortedEngines.filter(function (engine) {
  2519.                                         return !engine.hidden;
  2520.                                       });
  2521.   },
  2522.  
  2523.   // nsIBrowserSearchService
  2524.   getEngines: function SRCH_SVC_getEngines(aCount) {
  2525.     LOG("getEngines: getting all engines");
  2526.     var engines = this._getSortedEngines(true);
  2527.     aCount.value = engines.length;
  2528.     return engines;
  2529.   },
  2530.  
  2531.   getVisibleEngines: function SRCH_SVC_getVisible(aCount) {
  2532.     LOG("getVisibleEngines: getting all visible engines");
  2533.     var engines = this._getSortedEngines(false);
  2534.     aCount.value = engines.length;
  2535.     return engines;
  2536.   },
  2537.  
  2538.   getDefaultEngines: function SRCH_SVC_getDefault(aCount) {
  2539.     function isDefault(engine) {
  2540.       return engine._isDefault;
  2541.     };
  2542.     var engines = this._sortedEngines.filter(isDefault);
  2543.     var engineOrder = {};
  2544.     var engineName;
  2545.     var i = 1;
  2546.  
  2547.     // Build a list of engines which we have ordering information for.
  2548.     // We're rebuilding the list here because _sortedEngines contain the
  2549.     // current order, but we want the original order.
  2550.  
  2551.     // First, look at the "browser.search.order.extra" branch.
  2552.     try {
  2553.       var prefB = Cc["@mozilla.org/preferences-service;1"].
  2554.                   getService(Ci.nsIPrefBranch);
  2555.       var extras = prefB.getChildList(BROWSER_SEARCH_PREF + "order.extra.",
  2556.                                       {});
  2557.  
  2558.       for each (var prefName in extras) {
  2559.         engineName = prefB.getCharPref(prefName);
  2560.  
  2561.         if (!(engineName in engineOrder))
  2562.           engineOrder[engineName] = i++;
  2563.       }
  2564.     } catch (e) {
  2565.       LOG("Getting extra order prefs failed: " + e);
  2566.     }
  2567.  
  2568.     // Now look through the "browser.search.order" branch.
  2569.     for (var j = 1; ; j++) {
  2570.       engineName = getLocalizedPref(BROWSER_SEARCH_PREF + "order." + j);
  2571.       if (!engineName)
  2572.         break;
  2573.  
  2574.       if (!(engineName in engineOrder))
  2575.         engineOrder[engineName] = i++;
  2576.     }
  2577.  
  2578.     LOG("getDefaultEngines: engineOrder: " + engineOrder.toSource());
  2579.  
  2580.     function compareEngines (a, b) {
  2581.       var aIdx = engineOrder[a.name];
  2582.       var bIdx = engineOrder[b.name];
  2583.  
  2584.       if (aIdx && bIdx)
  2585.         return aIdx - bIdx;
  2586.       if (aIdx)
  2587.         return -1;
  2588.       if (bIdx)
  2589.         return 1;
  2590.  
  2591.       return a.name.localeCompare(b.name);
  2592.     }
  2593.     engines.sort(compareEngines);
  2594.  
  2595.     aCount.value = engines.length;
  2596.     return engines;
  2597.   },
  2598.  
  2599.   getEngineByName: function SRCH_SVC_getEngineByName(aEngineName) {
  2600.     return this._engines[aEngineName] || null;
  2601.   },
  2602.  
  2603.   getEngineByAlias: function SRCH_SVC_getEngineByAlias(aAlias) {
  2604.     for (var engineName in this._engines) {
  2605.       var engine = this._engines[engineName];
  2606.       if (engine && engine.alias == aAlias)
  2607.         return engine;
  2608.     }
  2609.     return null;
  2610.   },
  2611.  
  2612.   addEngineWithDetails: function SRCH_SVC_addEWD(aName, aIconURL, aAlias,
  2613.                                                  aDescription, aMethod,
  2614.                                                  aTemplate) {
  2615.     ENSURE_ARG(aName, "Invalid name passed to addEngineWithDetails!");
  2616.     ENSURE_ARG(aMethod, "Invalid method passed to addEngineWithDetails!");
  2617.     ENSURE_ARG(aTemplate, "Invalid template passed to addEngineWithDetails!");
  2618.  
  2619.     ENSURE(!this._engines[aName], "An engine with that name already exists!",
  2620.            Cr.NS_ERROR_FILE_ALREADY_EXISTS);
  2621.  
  2622.     var engine = new Engine(getSanitizedFile(aName), SEARCH_DATA_XML, false);
  2623.     engine._initFromMetadata(aName, aIconURL, aAlias, aDescription,
  2624.                              aMethod, aTemplate);
  2625.     this._addEngineToStore(engine);
  2626.   },
  2627.  
  2628.   addEngine: function SRCH_SVC_addEngine(aEngineURL, aDataType, aIconURL,
  2629.                                          aConfirm) {
  2630.     LOG("addEngine: Adding \"" + aEngineURL + "\".");
  2631.     try {
  2632.       var uri = makeURI(aEngineURL);
  2633.       var engine = new Engine(uri, aDataType, false);
  2634.       engine._initFromURI();
  2635.     } catch (ex) {
  2636.       LOG("addEngine: Error adding engine:\n" + ex);
  2637.       throw Cr.NS_ERROR_FAILURE;
  2638.     }
  2639.     engine._setIcon(aIconURL, false);
  2640.     engine._confirm = aConfirm;
  2641.   },
  2642.  
  2643.   removeEngine: function SRCH_SVC_removeEngine(aEngine) {
  2644.     ENSURE_ARG(aEngine, "no engine passed to removeEngine!");
  2645.  
  2646.     var engineToRemove = null;
  2647.     for (var e in this._engines)
  2648.       if (aEngine.wrappedJSObject == this._engines[e])
  2649.         engineToRemove = this._engines[e];
  2650.  
  2651.     ENSURE(engineToRemove, "removeEngine: Can't find engine to remove!",
  2652.            Cr.NS_ERROR_FILE_NOT_FOUND);
  2653.  
  2654.     if (engineToRemove == this.currentEngine)
  2655.       this._currentEngine = null;
  2656.  
  2657.     if (engineToRemove._readOnly) {
  2658.       // Just hide it (the "hidden" setter will notify) and remove its alias to
  2659.       // avoid future conflicts with other engines.
  2660.       engineToRemove.hidden = true;
  2661.       engineToRemove.alias = null;
  2662.     } else {
  2663.       // Remove the engine file from disk (this might throw)
  2664.       engineToRemove._remove();
  2665.       engineToRemove._file = null;
  2666.  
  2667.       // Remove the engine from _sortedEngines
  2668.       var index = this._sortedEngines.indexOf(engineToRemove);
  2669.       ENSURE(index != -1, "Can't find engine to remove in _sortedEngines!",
  2670.              Cr.NS_ERROR_FAILURE);
  2671.       this._sortedEngines.splice(index, 1);
  2672.  
  2673.       // Remove the engine from the internal store
  2674.       delete this._engines[engineToRemove.name];
  2675.  
  2676.       notifyAction(engineToRemove, SEARCH_ENGINE_REMOVED);
  2677.  
  2678.       // Since we removed an engine, we need to update the preferences.
  2679.       this._needToSetOrderPrefs = true;
  2680.     }
  2681.   },
  2682.  
  2683.   moveEngine: function SRCH_SVC_moveEngine(aEngine, aNewIndex) {
  2684.     ENSURE_ARG((aNewIndex < this._sortedEngines.length) && (aNewIndex >= 0),
  2685.                "SRCH_SVC_moveEngine: Index out of bounds!");
  2686.     ENSURE_ARG(aEngine instanceof Ci.nsISearchEngine,
  2687.                "SRCH_SVC_moveEngine: Invalid engine passed to moveEngine!");
  2688.     ENSURE(!aEngine.hidden, "moveEngine: Can't move a hidden engine!",
  2689.            Cr.NS_ERROR_FAILURE);
  2690.  
  2691.     var engine = aEngine.wrappedJSObject;
  2692.  
  2693.     var currentIndex = this._sortedEngines.indexOf(engine);
  2694.     ENSURE(currentIndex != -1, "moveEngine: Can't find engine to move!",
  2695.            Cr.NS_ERROR_UNEXPECTED);
  2696.  
  2697.     // Our callers only take into account non-hidden engines when calculating
  2698.     // aNewIndex, but we need to move it in the array of all engines, so we
  2699.     // need to adjust aNewIndex accordingly. To do this, we count the number
  2700.     // of hidden engines in the list before the engine that we're taking the
  2701.     // place of. We do this by first finding newIndexEngine (the engine that
  2702.     // we were supposed to replace) and then iterating through the complete 
  2703.     // engine list until we reach it, increasing aNewIndex for each hidden
  2704.     // engine we find on our way there.
  2705.     //
  2706.     // This could be further simplified by having our caller pass in
  2707.     // newIndexEngine directly instead of aNewIndex.
  2708.     var newIndexEngine = this._getSortedEngines(false)[aNewIndex];
  2709.     ENSURE(newIndexEngine, "moveEngine: Can't find engine to replace!",
  2710.            Cr.NS_ERROR_UNEXPECTED);
  2711.  
  2712.     for (var i = 0; i < this._sortedEngines.length; ++i) {
  2713.       if (newIndexEngine == this._sortedEngines[i])
  2714.         break;
  2715.       if (this._sortedEngines[i].hidden)
  2716.         aNewIndex++;
  2717.     }
  2718.  
  2719.     if (currentIndex == aNewIndex)
  2720.       return; // nothing to do!
  2721.  
  2722.     // Move the engine
  2723.     var movedEngine = this._sortedEngines.splice(currentIndex, 1)[0];
  2724.     this._sortedEngines.splice(aNewIndex, 0, movedEngine);
  2725.  
  2726.     notifyAction(engine, SEARCH_ENGINE_CHANGED);
  2727.  
  2728.     // Since we moved an engine, we need to update the preferences.
  2729.     this._needToSetOrderPrefs = true;
  2730.   },
  2731.  
  2732.   restoreDefaultEngines: function SRCH_SVC_resetDefaultEngines() {
  2733.     for each (var e in this._engines) {
  2734.       // Unhide all default engines
  2735.       if (e.hidden && e._isDefault)
  2736.         e.hidden = false;
  2737.     }
  2738.   },
  2739.  
  2740.   get defaultEngine() {
  2741.     const defPref = BROWSER_SEARCH_PREF + "defaultenginename";
  2742.     // Get the default engine - this pref should always exist, but the engine
  2743.     // might be hidden
  2744.     this._defaultEngine = this.getEngineByName(getLocalizedPref(defPref, ""));
  2745.     if (!this._defaultEngine || this._defaultEngine.hidden)
  2746.       this._defaultEngine = this._getSortedEngines(false)[0] || null;
  2747.     return this._defaultEngine;
  2748.   },
  2749.  
  2750.   get currentEngine() {
  2751.     if (!this._currentEngine || this._currentEngine.hidden)
  2752.       this._currentEngine = this.defaultEngine;
  2753.     return this._currentEngine;
  2754.   },
  2755.   set currentEngine(val) {
  2756.     ENSURE_ARG(val instanceof Ci.nsISearchEngine,
  2757.                "Invalid argument passed to currentEngine setter");
  2758.  
  2759.     var newCurrentEngine = this.getEngineByName(val.name);
  2760.     ENSURE(newCurrentEngine, "Can't find engine in store!",
  2761.            Cr.NS_ERROR_UNEXPECTED);
  2762.  
  2763.     this._currentEngine = newCurrentEngine;
  2764.  
  2765.     var currentEnginePref = BROWSER_SEARCH_PREF + "selectedEngine";
  2766.  
  2767.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  2768.       getService(Ci.nsIPrefService).QueryInterface(Ci.nsIPrefBranch);
  2769.  
  2770.     if (this._currentEngine == this.defaultEngine) {
  2771.       if (prefB.prefHasUserValue(currentEnginePref))
  2772.         prefB.clearUserPref(currentEnginePref);
  2773.     }
  2774.     else {
  2775.       setLocalizedPref(currentEnginePref, this._currentEngine.name);
  2776.     }
  2777.  
  2778.     notifyAction(this._currentEngine, SEARCH_ENGINE_CURRENT);
  2779.   },
  2780.  
  2781.   // nsIObserver
  2782.   observe: function SRCH_SVC_observe(aEngine, aTopic, aVerb) {
  2783.     switch (aTopic) {
  2784.       case SEARCH_ENGINE_TOPIC:
  2785.         if (aVerb == SEARCH_ENGINE_LOADED) {
  2786.           var engine = aEngine.QueryInterface(Ci.nsISearchEngine);
  2787.           LOG("nsSearchService::observe: Done installation of " + engine.name
  2788.               + ".");
  2789.           this._addEngineToStore(engine.wrappedJSObject);
  2790.           if (engine.wrappedJSObject._useNow) {
  2791.             LOG("nsSearchService::observe: setting current");
  2792.             this.currentEngine = aEngine;
  2793.           }
  2794.         }
  2795.         break;
  2796.       case QUIT_APPLICATION_TOPIC:
  2797.         this._removeObservers();
  2798.         this._saveSortedEngineList();
  2799.         break;
  2800.     }
  2801.   },
  2802.  
  2803.   _addObservers: function SRCH_SVC_addObservers() {
  2804.     var os = Cc["@mozilla.org/observer-service;1"].
  2805.              getService(Ci.nsIObserverService);
  2806.     os.addObserver(this, SEARCH_ENGINE_TOPIC, false);
  2807.     os.addObserver(this, QUIT_APPLICATION_TOPIC, false);
  2808.   },
  2809.  
  2810.   _removeObservers: function SRCH_SVC_removeObservers() {
  2811.     var os = Cc["@mozilla.org/observer-service;1"].
  2812.              getService(Ci.nsIObserverService);
  2813.     os.removeObserver(this, SEARCH_ENGINE_TOPIC);
  2814.     os.removeObserver(this, QUIT_APPLICATION_TOPIC);
  2815.   },
  2816.  
  2817.   QueryInterface: function SRCH_SVC_QI(aIID) {
  2818.     if (aIID.equals(Ci.nsIBrowserSearchService) ||
  2819.         aIID.equals(Ci.nsIObserver)             ||
  2820.         aIID.equals(Ci.nsISupports))
  2821.       return this;
  2822.     throw Cr.NS_ERROR_NO_INTERFACE;
  2823.   }
  2824. };
  2825.  
  2826. var engineMetadataService = {
  2827.   init: function epsInit() {
  2828.     var engineDataTable = "id INTEGER PRIMARY KEY, engineid STRING, name STRING, value STRING";
  2829.     var file = getDir(NS_APP_USER_PROFILE_50_DIR);
  2830.     file.append("search.sqlite");
  2831.     var dbService = Cc["@mozilla.org/storage/service;1"].
  2832.                     getService(Ci.mozIStorageService);
  2833.     try {
  2834.         this.mDB = dbService.openDatabase(file);
  2835.     } catch (ex) {
  2836.         if (ex.result == 0x8052000b) { /* NS_ERROR_FILE_CORRUPTED */
  2837.             // delete and try again
  2838.             file.remove(false);
  2839.             this.mDB = dbService.openDatabase(file);
  2840.         } else {
  2841.             throw ex;
  2842.         }
  2843.     }
  2844.  
  2845.     try {
  2846.       this.mDB.createTable("engine_data", engineDataTable);
  2847.     } catch (ex) {
  2848.       // Fails if the table already exists, which is fine
  2849.     }
  2850.  
  2851.     this.mGetData = createStatement (
  2852.       this.mDB,
  2853.       "SELECT value FROM engine_data WHERE engineid = :engineid AND name = :name");
  2854.     this.mDeleteData = createStatement (
  2855.       this.mDB,
  2856.       "DELETE FROM engine_data WHERE engineid = :engineid AND name = :name");
  2857.     this.mInsertData = createStatement (
  2858.       this.mDB,
  2859.       "INSERT INTO engine_data (engineid, name, value) " +
  2860.       "VALUES (:engineid, :name, :value)");
  2861.   },
  2862.   getAttr: function epsGetAttr(engine, name) {
  2863.      // attr names must be lower case
  2864.      name = name.toLowerCase();
  2865.  
  2866.     var stmt = this.mGetData;
  2867.     stmt.reset();
  2868.     var pp = stmt.params;
  2869.     pp.engineid = engine._id;
  2870.     pp.name = name;
  2871.  
  2872.     var value = null;
  2873.     if (stmt.step())
  2874.       value = stmt.row.value;
  2875.     stmt.reset();
  2876.     return value;
  2877.   },
  2878.  
  2879.   setAttr: function epsSetAttr(engine, name, value) {
  2880.     // attr names must be lower case
  2881.     name = name.toLowerCase();
  2882.  
  2883.     this.mDB.beginTransaction();
  2884.  
  2885.     var pp = this.mDeleteData.params;
  2886.     pp.engineid = engine._id;
  2887.     pp.name = name;
  2888.     this.mDeleteData.step();
  2889.     this.mDeleteData.reset();
  2890.  
  2891.     pp = this.mInsertData.params;
  2892.     pp.engineid = engine._id;
  2893.     pp.name = name;
  2894.     pp.value = value;
  2895.     this.mInsertData.step();
  2896.     this.mInsertData.reset();
  2897.  
  2898.     this.mDB.commitTransaction();
  2899.   },
  2900.  
  2901.   setAttrs: function epsSetAttrs(engines, names, values) {
  2902.     this.mDB.beginTransaction();
  2903.  
  2904.     for (var i = 0; i < engines.length; i++) {
  2905.       // attr names must be lower case
  2906.       var name = names[i].toLowerCase();
  2907.  
  2908.       var pp = this.mDeleteData.params;
  2909.       pp.engineid = engines[i]._id;
  2910.       pp.name = names[i];
  2911.       this.mDeleteData.step();
  2912.       this.mDeleteData.reset();
  2913.  
  2914.       pp = this.mInsertData.params;
  2915.       pp.engineid = engines[i]._id;
  2916.       pp.name = names[i];
  2917.       pp.value = values[i];
  2918.       this.mInsertData.step();
  2919.       this.mInsertData.reset();
  2920.     }
  2921.  
  2922.     this.mDB.commitTransaction();
  2923.   },
  2924.  
  2925.   deleteEngineData: function epsDelData(engine, name) {
  2926.     // attr names must be lower case
  2927.     name = name.toLowerCase();
  2928.  
  2929.     var pp = this.mDeleteData.params;
  2930.     pp.engineid = engine._id;
  2931.     pp.name = name;
  2932.     this.mDeleteData.step();
  2933.     this.mDeleteData.reset();
  2934.   }
  2935. }
  2936.  
  2937. const SEARCH_UPDATE_LOG_PREFIX = "*** Search update: ";
  2938.  
  2939. /**
  2940.  * Outputs aText to the JavaScript console as well as to stdout, if the search
  2941.  * logging pref (browser.search.update.log) is set to true.
  2942.  */
  2943. function ULOG(aText) {
  2944.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  2945.               getService(Ci.nsIPrefBranch);
  2946.   var shouldLog = false;
  2947.   try {
  2948.     shouldLog = prefB.getBoolPref(BROWSER_SEARCH_PREF + "update.log");
  2949.   } catch (ex) {}
  2950.  
  2951.   if (shouldLog) {
  2952.     dump(SEARCH_UPDATE_LOG_PREFIX + aText + "\n");
  2953.     var consoleService = Cc["@mozilla.org/consoleservice;1"].
  2954.                          getService(Ci.nsIConsoleService);
  2955.     consoleService.logStringMessage(aText);
  2956.   }
  2957. }
  2958.  
  2959. var engineUpdateService = {
  2960.   init: function eus_init() {
  2961.     var tm = Cc["@mozilla.org/updates/timer-manager;1"].
  2962.              getService(Ci.nsIUpdateTimerManager);
  2963.     // figure out how often to check for any expired engines
  2964.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  2965.                 getService(Ci.nsIPrefBranch);
  2966.     var interval = prefB.getIntPref(BROWSER_SEARCH_PREF + "updateinterval");
  2967.  
  2968.     // Interval is stored in hours
  2969.     var seconds = interval * 3600;
  2970.     tm.registerTimer("search-engine-update-timer", engineUpdateService,
  2971.                      seconds);
  2972.   },
  2973.  
  2974.   scheduleNextUpdate: function eus_scheduleNextUpdate(aEngine) {
  2975.     var interval = aEngine._updateInterval || SEARCH_DEFAULT_UPDATE_INTERVAL;
  2976.     var milliseconds = interval * 86400000; // |interval| is in days
  2977.     engineMetadataService.setAttr(aEngine, "updateexpir",
  2978.                                   Date.now() + milliseconds);
  2979.   },
  2980.  
  2981.   notify: function eus_Notify(aTimer) {
  2982.     ULOG("notify called");
  2983.  
  2984.     if (!getBoolPref(BROWSER_SEARCH_PREF + "update", true))
  2985.       return;
  2986.  
  2987.     // Our timer has expired, but unfortunately, we can't get any data from it.
  2988.     // Therefore, we need to walk our engine-list, looking for expired engines
  2989.     var searchService = Cc["@mozilla.org/browser/search-service;1"].
  2990.                         getService(Ci.nsIBrowserSearchService);
  2991.     var currentTime = Date.now();
  2992.     ULOG("currentTime: " + currentTime);
  2993.     for each (engine in searchService.getEngines({})) {
  2994.       engine = engine.wrappedJSObject;
  2995.       if (!engine._hasUpdates || engine._readOnly)
  2996.         continue;
  2997.  
  2998.       ULOG("checking " + engine.name);
  2999.  
  3000.       var expirTime = engineMetadataService.getAttr(engine, "updateexpir");
  3001.       var updateURL = engine._updateURL;
  3002.       var iconUpdateURL = engine._iconUpdateURL;
  3003.       ULOG("expirTime: " + expirTime + "\nupdateURL: " + updateURL +
  3004.            "\niconUpdateURL: " + iconUpdateURL);
  3005.  
  3006.       var engineExpired = expirTime <= currentTime;
  3007.  
  3008.       if (!expirTime || !engineExpired) {
  3009.         ULOG("skipping engine");
  3010.         continue;
  3011.       }
  3012.  
  3013.       ULOG(engine.name + " has expired");
  3014.  
  3015.       var testEngine = null;
  3016.  
  3017.       var updateURI = makeURI(updateURL);
  3018.       if (updateURI) {
  3019.         var dataType = engineMetadataService.getAttr(engine, "updatedatatype")
  3020.         if (!dataType) {
  3021.           ULOG("No loadtype to update engine!");
  3022.           continue;
  3023.         }
  3024.  
  3025.         testEngine = new Engine(updateURI, dataType, false);
  3026.         testEngine._engineToUpdate = engine;
  3027.         testEngine._initFromURI();
  3028.       } else
  3029.         ULOG("invalid updateURI");
  3030.  
  3031.       if (iconUpdateURL) {
  3032.         // If we're updating the engine too, use the new engine object,
  3033.         // otherwise use the existing engine object.
  3034.         (testEngine || engine)._setIcon(iconUpdateURL, true);
  3035.       }
  3036.  
  3037.       // Schedule the next update
  3038.       this.scheduleNextUpdate(engine);
  3039.  
  3040.     } // end engine iteration
  3041.   }
  3042. };
  3043.  
  3044. const kClassID    = Components.ID("{7319788a-fe93-4db3-9f39-818cf08f4256}");
  3045. const kClassName  = "Browser Search Service";
  3046. const kContractID = "@mozilla.org/browser/search-service;1";
  3047.  
  3048. // nsIFactory
  3049. const kFactory = {
  3050.   createInstance: function (outer, iid) {
  3051.     if (outer != null)
  3052.       throw Cr.NS_ERROR_NO_AGGREGATION;
  3053.     return (new SearchService()).QueryInterface(iid);
  3054.   }
  3055. };
  3056.  
  3057. // nsIModule
  3058. const gModule = {
  3059.   registerSelf: function (componentManager, fileSpec, location, type) {
  3060.     componentManager.QueryInterface(Ci.nsIComponentRegistrar);
  3061.     componentManager.registerFactoryLocation(kClassID,
  3062.                                              kClassName,
  3063.                                              kContractID,
  3064.                                              fileSpec, location, type);
  3065.   },
  3066.  
  3067.   unregisterSelf: function(componentManager, fileSpec, location) {
  3068.     componentManager.QueryInterface(Ci.nsIComponentRegistrar);
  3069.     componentManager.unregisterFactoryLocation(kClassID, fileSpec);
  3070.   },
  3071.  
  3072.   getClassObject: function (componentManager, cid, iid) {
  3073.     if (!cid.equals(kClassID))
  3074.       throw Cr.NS_ERROR_NO_INTERFACE;
  3075.     if (!iid.equals(Ci.nsIFactory))
  3076.       throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  3077.     return kFactory;
  3078.   },
  3079.  
  3080.   canUnload: function (componentManager) {
  3081.     return true;
  3082.   }
  3083. };
  3084.  
  3085. function NSGetModule(componentManager, fileSpec) {
  3086.   return gModule;
  3087. }
  3088.  
  3089. //@line 44 "e:\builds\tinderbox\Fx-Rel\WINNT_5.2_Depend\mozilla\toolkit\content\debug.js"
  3090.  
  3091. var gTraceOnAssert = true;
  3092.  
  3093. /**
  3094.  * This function provides a simple assertion function for JavaScript.
  3095.  * If the condition is true, this function will do nothing.  If the
  3096.  * condition is false, then the message will be printed to the console
  3097.  * and an alert will appear showing a stack trace, so that the (alpha
  3098.  * or nightly) user can file a bug containing it.  For future enhancements, 
  3099.  * see bugs 330077 and 330078.
  3100.  *
  3101.  * To suppress the dialogs, you can run with the environment variable
  3102.  * XUL_ASSERT_PROMPT set to 0 (if unset, this defaults to 1).
  3103.  *
  3104.  * @param condition represents the condition that we're asserting to be
  3105.  *                  true when we call this function--should be
  3106.  *                  something that can be evaluated as a boolean.
  3107.  * @param message   a string to be displayed upon failure of the assertion
  3108.  */
  3109.  
  3110. function NS_ASSERT(condition, message) {
  3111.   if (condition)
  3112.     return;
  3113.  
  3114.   var releaseBuild = true;
  3115.   var defB = Components.classes["@mozilla.org/preferences-service;1"]
  3116.                        .getService(Components.interfaces.nsIPrefService)
  3117.                        .getDefaultBranch(null);
  3118.   try {
  3119.     switch (defB.getCharPref("app.update.channel")) {
  3120.       case "nightly":
  3121.       case "beta":
  3122.       case "default":
  3123.         releaseBuild = false;
  3124.     }
  3125.   } catch(ex) {}
  3126.  
  3127.   var caller = arguments.callee.caller;
  3128.   var assertionText = "ASSERT: " + message + "\n";
  3129.  
  3130.   if (releaseBuild) {
  3131.     // Just report the error to the console
  3132.     Components.utils.reportError(assertionText);
  3133.     return;
  3134.   }
  3135.  
  3136.   // Otherwise, dump to stdout and launch an assertion failure dialog
  3137.   dump(assertionText);
  3138.  
  3139.   var stackText = "";
  3140.   if (gTraceOnAssert) {
  3141.     stackText = "Stack Trace: \n";
  3142.     var count = 0;
  3143.     while (caller) {
  3144.       stackText += count++ + ":" + caller.name + "(";
  3145.       for (var i = 0; i < caller.arguments.length; ++i) {
  3146.         var arg = caller.arguments[i];
  3147.         stackText += arg;
  3148.         if (i < caller.arguments.length - 1)
  3149.           stackText += ",";
  3150.       }
  3151.       stackText += ")\n";
  3152.       caller = caller.arguments.callee.caller;
  3153.     }
  3154.   }
  3155.  
  3156.   var environment = Components.classes["@mozilla.org/process/environment;1"].
  3157.                     getService(Components.interfaces.nsIEnvironment);
  3158.   if (environment.exists("XUL_ASSERT_PROMPT") &&
  3159.       !parseInt(environment.get("XUL_ASSERT_PROMPT")))
  3160.     return;
  3161.  
  3162.   var source = null;
  3163.   if (this.window)
  3164.     source = window;
  3165.   var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].
  3166.            getService(Components.interfaces.nsIPromptService);
  3167.   ps.alert(source, "Assertion Failed", assertionText + stackText);
  3168. }
  3169.